Skip to content

Commit f1e36e7

Browse files
committed
Add support to make relation for ObjectID with hasMany and hasOne mongodb#2
1 parent dfaa7dd commit f1e36e7

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

src/Jenssegers/Mongodb/Relations/EmbedsOneOrMany.php

+1
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,7 @@ public function match(array $models, Collection $results, $relation)
8282
{
8383
foreach ($models as $model) {
8484
$results = $model->$relation()->getResults();
85+
dd($results);
8586

8687
$model->setParentRelation($this);
8788

src/Jenssegers/Mongodb/Relations/HasOneOrManyTrait.php

+45
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
* @package Jenssegers\Mongodb\Relations
1717
*
1818
* @property \Illuminate\Database\Eloquent\Builder $query
19+
* @property string $localKey
1920
*/
2021
trait HasOneOrManyTrait
2122
{
@@ -32,4 +33,48 @@ public function addConstraints()
3233
$this->query->whereNotNull($this->foreignKey);
3334
}
3435
}
36+
37+
/**
38+
* @inheritdoc
39+
*/
40+
public function addEagerConstraints(array $models)
41+
{
42+
// We'll grab the primary key name of the related models since it could be set to
43+
// a non-standard name and not "id". We will then construct the constraint for
44+
// our eagerly loading query so it returns the proper models from execution.
45+
$key = $this->foreignKey;
46+
47+
$this->query->whereIn($key, $this->getEagerModelKeys($models));
48+
}
49+
50+
/**
51+
* Gather the keys from an array of related models.
52+
*
53+
* @param array $models
54+
* @return array
55+
*/
56+
protected function getEagerModelKeys(array $models)
57+
{
58+
$keys = [];
59+
60+
// First we need to gather all of the keys from the parent models so we know what
61+
// to query for via the eager loading query. We will add them to an array then
62+
// execute a "where in" statement to gather up all of those related records.
63+
foreach ($models as $model) {
64+
if (! is_null($value = $model->{$this->localKey})) {
65+
$keys[] = new ObjectID($value);
66+
}
67+
}
68+
69+
// If there are no keys that were not null we will just return an array with null
70+
// so this query wont fail plus returns zero results, which should be what the
71+
// developer expects to happen in this situation. Otherwise we'll sort them.
72+
if (count($keys) === 0) {
73+
return [null];
74+
}
75+
76+
sort($keys);
77+
78+
return array_values(array_unique($keys));
79+
}
3580
}

0 commit comments

Comments
 (0)