diff --git a/src/Relations/BelongsToThrough.php b/src/Relations/BelongsToThrough.php index ef255fe..48a4972 100644 --- a/src/Relations/BelongsToThrough.php +++ b/src/Relations/BelongsToThrough.php @@ -67,8 +67,6 @@ public function __construct(Builder $query, Model $parent, array $throughParents */ public function addConstraints() { - $this->query->select([$this->related->getTable().'.*']); - $this->performJoins(); if (static::$constraints) { @@ -141,10 +139,6 @@ public function hasSoftDeletes(Model $model) */ public function addEagerConstraints(array $models) { - $this->query->addSelect([ - $this->getQualifiedFirstLocalKeyName().' as '.static::THROUGH_KEY, - ]); - $keys = $this->getKeys($models, $this->getFirstForeignKeyName()); $this->query->whereIn($this->getQualifiedFirstLocalKeyName(), $keys); @@ -215,7 +209,43 @@ protected function buildDictionary(Collection $results) */ public function getResults() { - return $this->query->first(); + return $this->first(); + } + + /** + * Execute the query and get the first result. + * + * @param array $columns + * @return \Illuminate\Database\Eloquent\Model|object|static|null + */ + public function first($columns = ['*']) + { + if ($columns === ['*']) { + $columns = [$this->related->getTable().'.*']; + } + + return $this->query->first($columns); + } + + /** + * Execute the query as a "select" statement. + * + * @param array $columns + * @return \Illuminate\Database\Eloquent\Collection + */ + public function get($columns = ['*']) + { + $columns = $this->query->getQuery()->columns ? [] : $columns; + + if ($columns === ['*']) { + $columns = [$this->related->getTable().'.*']; + } + + $columns[] = $this->getQualifiedFirstLocalKeyName().' as '.static::THROUGH_KEY; + + $this->query->addSelect($columns); + + return $this->query->get(); } /** diff --git a/tests/BelongsToThroughTest.php b/tests/BelongsToThroughTest.php index 5666787..943c89c 100644 --- a/tests/BelongsToThroughTest.php +++ b/tests/BelongsToThroughTest.php @@ -12,6 +12,7 @@ public function testLazyLoading() $country = Comment::first()->country; $this->assertEquals(1, $country->id); + $this->assertEquals(1, $country->users_count); } public function testLazyLoadingWithSingleThroughModel() @@ -49,6 +50,7 @@ public function testEagerLoading() $this->assertEquals(1, $comments[0]->country->id); $this->assertEquals(2, $comments[1]->country->id); $this->assertNull($comments[2]->country); + $this->assertEquals(1, $comments[0]->country->users_count); } public function testEagerLoadingWithPrefix() diff --git a/tests/Models/Country.php b/tests/Models/Country.php index bf9a9b0..28df4d7 100644 --- a/tests/Models/Country.php +++ b/tests/Models/Country.php @@ -4,5 +4,10 @@ class Country extends Model { + protected $withCount = ['users']; + public function users() + { + return $this->hasMany(User::class); + } }