Skip to content

Commit

Permalink
cleanup hasOne and belongsToOne
Browse files Browse the repository at this point in the history
  • Loading branch information
kevindees committed Aug 5, 2022
1 parent bac282d commit 9f0b0a4
Showing 1 changed file with 16 additions and 7 deletions.
23 changes: 16 additions & 7 deletions src/Models/Model.php
Original file line number Diff line number Diff line change
Expand Up @@ -1967,15 +1967,14 @@ public function getCast( $property )
*/
public function hasOne($modelClass, $id_foreign = null, $scope = null)
{
$id = $this->getID();
/** @var Model $relationship */
$relationship = new $modelClass;
$relationship->setRelatedModel( $this );

if( ! $id_foreign && $this->resource ) {
$id_foreign = $this->resource . '_id';
}

/** @var Model $relationship */
$relationship = new $modelClass;
$relationship->setRelatedModel( $this );
$relationship->relatedBy = [
'type' => 'hasOne',
'query' => [
Expand All @@ -1986,7 +1985,12 @@ public function hasOne($modelClass, $id_foreign = null, $scope = null)
]
];

return $relationship->findAll()->where( $id_foreign, $id)->take(1);
if(is_callable($scope)) {
$scope($relationship);
}

$id = $this->getID();
return $relationship->where( $id_foreign, $id)->take(1);
}

/**
Expand All @@ -2003,6 +2007,11 @@ public function belongsTo($modelClass, $id_local = null, $scope = null)
/** @var Model $relationship */
$relationship = new $modelClass;
$relationship->setRelatedModel( $this );

if( ! $id_local && $relationship->resource ) {
$id_local = $relationship->resource . '_id';
}

$relationship->relatedBy = [
'type' => 'belongsTo',
'query' => [
Expand All @@ -2013,8 +2022,8 @@ public function belongsTo($modelClass, $id_local = null, $scope = null)
]
];

if( ! $id_local && $relationship->resource ) {
$id_local = $relationship->resource . '_id';
if(is_callable($scope)) {
$scope($relationship);
}

$id = $this->getProperty( $id_local );
Expand Down

0 comments on commit 9f0b0a4

Please sign in to comment.