diff --git a/src/LaravelBook/Ardent/Ardent.php b/src/LaravelBook/Ardent/Ardent.php index 49386fd..1c0ccd9 100755 --- a/src/LaravelBook/Ardent/Ardent.php +++ b/src/LaravelBook/Ardent/Ardent.php @@ -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; @@ -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 + ); + } } /**