16
16
* @package Jenssegers\Mongodb\Relations
17
17
*
18
18
* @property \Illuminate\Database\Eloquent\Builder $query
19
+ * @property string $localKey
19
20
*/
20
21
trait HasOneOrManyTrait
21
22
{
@@ -32,4 +33,48 @@ public function addConstraints()
32
33
$ this ->query ->whereNotNull ($ this ->foreignKey );
33
34
}
34
35
}
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
+ }
35
80
}
0 commit comments