Skip to content

Added belongsTo functionality for Eloquent models #35

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions src/Bridges/Laravel/HasEloquentRelations.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,12 @@
use Cristal\ApiWrapper\Relations\RelationInterface;
use Cristal\ApiWrapper\Bridges\Laravel\Relations\HasOne as BridgeHasOne;
use Cristal\ApiWrapper\Bridges\Laravel\Relations\HasMany as BridgeHasMany;
use Cristal\ApiWrapper\Bridges\Laravel\Relations\BelongsTo as BridgeBelongsTo;
use Cristal\ApiWrapper\Bridges\Laravel\Relations\Builder as BridgeBuilder;
use Illuminate\Database\Eloquent\Model as Eloquent;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\Relation;
use LogicException;

Expand Down Expand Up @@ -60,6 +62,21 @@ public function hasOne($related, $foreignKey = null, $localKey = null)
return new BridgeHasOne($this, $instance, $foreignKey, $localKey);
}


public function belongsTo($related, $foreignKey = null, $ownerKey = null, $relationName = null)
{
$parent = $this->newRelatedInstance($related);

$foreignKey = $foreignKey ?: $parent->getForeignKey();
$ownerKey = $ownerKey ?: $parent->getKeyName();

if ($parent instanceof Eloquent) {
return new BelongsTo($parent->newQuery(), $this->createFakeEloquentModel(), $foreignKey, $ownerKey, $relationName);
}

return new BridgeBelongsTo($parent, $this, $foreignKey, $ownerKey);
}

/**
* @return BridgeBuilder
*/
Expand Down