77use Jenssegers \Mongodb \DatabaseManager as Resolver ;
88use Jenssegers \Mongodb \Builder as QueryBuilder ;
99use Jenssegers \Mongodb \Relations \BelongsTo ;
10+ use Jenssegers \Mongodb \Relations \BelongsToMany ;
1011
1112use Carbon \Carbon ;
1213use DateTime ;
@@ -199,6 +200,43 @@ public function belongsTo($related, $foreignKey = null, $otherKey = null, $relat
199200 return new BelongsTo ($ query , $ this , $ foreignKey , $ otherKey , $ relation );
200201 }
201202
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+
202240 /**
203241 * Get a new query builder instance for the connection.
204242 *
@@ -274,4 +312,4 @@ public function __call($method, $parameters)
274312 return parent ::__call ($ method , $ parameters );
275313 }
276314
277- }
315+ }
0 commit comments