3
3
namespace Jenssegers \Mongodb \Relations ;
4
4
5
5
use Illuminate \Database \Eloquent \Builder ;
6
+ use Illuminate \Database \Eloquent \Collection ;
6
7
use Illuminate \Database \Eloquent \Model as EloquentModel ;
7
8
8
9
class BelongsTo extends \Illuminate \Database \Eloquent \Relations \BelongsTo
@@ -25,7 +26,9 @@ public function addConstraints()
25
26
// For belongs to relationships, which are essentially the inverse of has one
26
27
// or has many relationships, we need to actually query on the primary key
27
28
// of the related models matching on the foreign key that's on a parent.
28
- $ this ->query ->where ($ this ->getOwnerKey (), '= ' , $ this ->parent ->{$ this ->foreignKey });
29
+ $ this ->query
30
+ ->where ($ this ->getOwnerKey (), '= ' , $ this ->parent ->{$ this ->foreignKey })
31
+ ->orWhere ($ this ->getOwnerKey ().'._id ' , '= ' , $ this ->parent ->{$ this ->foreignKey });
29
32
}
30
33
}
31
34
@@ -69,4 +72,34 @@ protected function whereInMethod(EloquentModel $model, $key)
69
72
{
70
73
return 'whereIn ' ;
71
74
}
75
+
76
+ /**
77
+ * @inheritDoc
78
+ */
79
+ public function match (array $ models , Collection $ results , $ relation )
80
+ {
81
+ $ foreign = $ this ->foreignKey ;
82
+
83
+ $ owner = $ this ->ownerKey ;
84
+
85
+ // First we will get to build a dictionary of the child models by their primary
86
+ // key of the relationship, then we can easily match the children back onto
87
+ // the parents using that dictionary and the primary key of the children.
88
+ $ dictionary = [];
89
+
90
+ foreach ($ results as $ result ) {
91
+ $ dictionary [$ result ->getAttribute ($ owner )] = $ result ;
92
+ }
93
+
94
+ // Once we have the dictionary constructed, we can loop through all the parents
95
+ // and match back onto their children using these keys of the dictionary and
96
+ // the primary key of the children to map them onto the correct instances.
97
+ foreach ($ models as $ model ) {
98
+ if (isset ($ dictionary [(string ) $ model ->{$ foreign }])) {
99
+ $ model ->setRelation ($ relation , $ dictionary [(string ) $ model ->{$ foreign }]);
100
+ }
101
+ }
102
+
103
+ return $ models ;
104
+ }
72
105
}
0 commit comments