From f1e36e73ac47821a18c5d7a35e23ddaf29be9fd1 Mon Sep 17 00:00:00 2001 From: Sangrak Choi Date: Wed, 15 Nov 2017 04:36:13 +0900 Subject: [PATCH] Add support to make relation for ObjectID with `hasMany` and `hasOne` #2 --- .../Mongodb/Relations/EmbedsOneOrMany.php | 1 + .../Mongodb/Relations/HasOneOrManyTrait.php | 45 +++++++++++++++++++ 2 files changed, 46 insertions(+) diff --git a/src/Jenssegers/Mongodb/Relations/EmbedsOneOrMany.php b/src/Jenssegers/Mongodb/Relations/EmbedsOneOrMany.php index 031548743..12ae67514 100644 --- a/src/Jenssegers/Mongodb/Relations/EmbedsOneOrMany.php +++ b/src/Jenssegers/Mongodb/Relations/EmbedsOneOrMany.php @@ -82,6 +82,7 @@ public function match(array $models, Collection $results, $relation) { foreach ($models as $model) { $results = $model->$relation()->getResults(); + dd($results); $model->setParentRelation($this); diff --git a/src/Jenssegers/Mongodb/Relations/HasOneOrManyTrait.php b/src/Jenssegers/Mongodb/Relations/HasOneOrManyTrait.php index fce7e5aeb..cc38206fc 100644 --- a/src/Jenssegers/Mongodb/Relations/HasOneOrManyTrait.php +++ b/src/Jenssegers/Mongodb/Relations/HasOneOrManyTrait.php @@ -16,6 +16,7 @@ * @package Jenssegers\Mongodb\Relations * * @property \Illuminate\Database\Eloquent\Builder $query + * @property string $localKey */ trait HasOneOrManyTrait { @@ -32,4 +33,48 @@ public function addConstraints() $this->query->whereNotNull($this->foreignKey); } } + + /** + * @inheritdoc + */ + public function addEagerConstraints(array $models) + { + // We'll grab the primary key name of the related models since it could be set to + // a non-standard name and not "id". We will then construct the constraint for + // our eagerly loading query so it returns the proper models from execution. + $key = $this->foreignKey; + + $this->query->whereIn($key, $this->getEagerModelKeys($models)); + } + + /** + * Gather the keys from an array of related models. + * + * @param array $models + * @return array + */ + protected function getEagerModelKeys(array $models) + { + $keys = []; + + // First we need to gather all of the keys from the parent models so we know what + // to query for via the eager loading query. We will add them to an array then + // execute a "where in" statement to gather up all of those related records. + foreach ($models as $model) { + if (! is_null($value = $model->{$this->localKey})) { + $keys[] = new ObjectID($value); + } + } + + // If there are no keys that were not null we will just return an array with null + // so this query wont fail plus returns zero results, which should be what the + // developer expects to happen in this situation. Otherwise we'll sort them. + if (count($keys) === 0) { + return [null]; + } + + sort($keys); + + return array_values(array_unique($keys)); + } } \ No newline at end of file