Skip to content
This repository has been archived by the owner on Jul 16, 2023. It is now read-only.

Update MorphTo to enable polymorphic eager loading #178

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
26 changes: 21 additions & 5 deletions src/LaravelBook/Ardent/Ardent.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
use Illuminate\Container\Container;
use Illuminate\Database\Capsule\Manager as DatabaseCapsule;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\MorphTo;
use Illuminate\Events\Dispatcher;
use Illuminate\Support\MessageBag;
use Illuminate\Support\Facades\Input;
Expand Down Expand Up @@ -410,14 +411,29 @@ public function morphTo($name = null, $type = null, $id = null) {
$name = snake_case($caller['function']);
}

// Next we will guess the type and ID if necessary. The type and IDs may also
// be passed into the function so that the developers may manually specify
// them on the relations. Otherwise, we will just make a great estimate.
list($type, $id) = $this->getMorphs($name, $type, $id);

$class = $this->$type;
// If the type value is null it is probably safe to assume we're eager loading
// the relationship. When that is the case we will pass in a dummy query as
// there are multiple types in the morph and we can't use single queries.
if (is_null($class = $this->$type))
{
return new MorphTo(
$this->newQuery(), $this, $id, null, $type, $name
);
}

return $this->belongsTo($class, $id);
// If we are not eager loading the relatinship, we will essentially treat this
// as a belongs-to style relationship since morph-to extends that class and
// we will pass in the appropriate values so that it behaves as expected.
else
{
$instance = new $class;

return new MorphTo(
with($instance)->newQuery(), $this, $id, $instance->getKeyName(), $type, $name
);
}
}

/**
Expand Down