From 0bb094ba2986b34f060d6ba2b8ab72d72d528fd3 Mon Sep 17 00:00:00 2001 From: Toby Zerner Date: Thu, 3 Oct 2019 15:54:47 +0930 Subject: [PATCH] Slight tweak/document Eloquent relationship ID loading --- src/Adapter/EloquentAdapter.php | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/src/Adapter/EloquentAdapter.php b/src/Adapter/EloquentAdapter.php index 552ac60..d016ad3 100644 --- a/src/Adapter/EloquentAdapter.php +++ b/src/Adapter/EloquentAdapter.php @@ -202,16 +202,19 @@ class EloquentAdapter implements AdapterInterface $property = $this->getRelationshipProperty($relationship); $relation = $models[0]->$property(); - if ($relation instanceof BelongsTo || $relation instanceof BelongsToMany) { + // If it's a belongs-to relationship, then the ID is stored on the model + // itself, so we don't need to load anything in advance. + if ($relation instanceof BelongsTo) { return; } (new Collection($models))->loadMissing([ $property => function ($query) use ($relation) { - $query->select([ - $relation->getRelated()->getKeyName(), - $relation->getForeignKeyName() - ]); + $query->select($relation->getRelated()->getKeyName()); + + if (! $relation instanceof BelongsToMany) { + $query->addSelect($relation->getForeignKeyName()); + } } ]); }