7
7
use Jenssegers \Mongodb \DatabaseManager as Resolver ;
8
8
use Jenssegers \Mongodb \Builder as QueryBuilder ;
9
9
use Jenssegers \Mongodb \Relations \BelongsTo ;
10
+ use Jenssegers \Mongodb \Relations \BelongsToMany ;
10
11
11
12
use Carbon \Carbon ;
12
13
use DateTime ;
@@ -199,6 +200,43 @@ public function belongsTo($related, $foreignKey = null, $otherKey = null, $relat
199
200
return new BelongsTo ($ query , $ this , $ foreignKey , $ otherKey , $ relation );
200
201
}
201
202
203
+ /**
204
+ * Define a many-to-many relationship.
205
+ *
206
+ * @param string $related
207
+ * @param string $table
208
+ * @param string $foreignKey
209
+ * @param string $otherKey
210
+ * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
211
+ */
212
+ public function belongsToMany ($ related , $ collection = null , $ foreignKey = null , $ otherKey = null )
213
+ {
214
+ $ caller = $ this ->getBelongsToManyCaller ();
215
+
216
+ // First, we'll need to determine the foreign key and "other key" for the
217
+ // relationship. Once we have determined the keys we'll make the query
218
+ // instances as well as the relationship instances we need for this.
219
+ $ foreignKey = $ foreignKey ?: $ this ->getForeignKey () . 's ' ;
220
+
221
+ $ instance = new $ related ;
222
+
223
+ $ otherKey = $ otherKey ?: $ instance ->getForeignKey () . 's ' ;
224
+ // If no table name was provided, we can guess it by concatenating the two
225
+ // models using underscores in alphabetical order. The two model names
226
+ // are transformed to snake case from their default CamelCase also.
227
+ if (is_null ($ collection ))
228
+ {
229
+ $ collection = snake_case (str_plural (class_basename ($ related )));
230
+ }
231
+
232
+ // Now we're ready to create a new query builder for the related model and
233
+ // the relationship instances for the relation. The relations will set
234
+ // appropriate query constraint and entirely manages the hydrations.
235
+ $ query = $ instance ->newQuery ();
236
+
237
+ return new BelongsToMany ($ query , $ this , $ collection , $ foreignKey , $ otherKey , $ caller ['function ' ]);
238
+ }
239
+
202
240
/**
203
241
* Get a new query builder instance for the connection.
204
242
*
@@ -274,4 +312,4 @@ public function __call($method, $parameters)
274
312
return parent ::__call ($ method , $ parameters );
275
313
}
276
314
277
- }
315
+ }
0 commit comments