@@ -201,40 +201,50 @@ public function belongsTo($related, $foreignKey = null, $otherKey = null, $relat
201201 }
202202
203203 /**
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 )
204+ * Define a many-to-many relationship.
205+ *
206+ * @param string $related
207+ * @param string $collection
208+ * @param string $foreignKey
209+ * @param string $otherKey
210+ * @param string $relation
211+ * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
212+ */
213+ public function belongsToMany ($ related , $ collection = null , $ foreignKey = null , $ otherKey = null , $ relation = null )
213214 {
214- $ caller = $ this ->getBelongsToManyCaller ();
215-
215+ // If no relationship name was passed, we will pull backtraces to get the
216+ // name of the calling function. We will use that function name as the
217+ // title of this relation since that is a great convention to apply.
218+ if (is_null ($ relation ))
219+ {
220+ $ caller = $ this ->getBelongsToManyCaller ();
221+
222+ $ name = $ caller ['function ' ];
223+ }
224+
216225 // First, we'll need to determine the foreign key and "other key" for the
217226 // relationship. Once we have determined the keys we'll make the query
218227 // instances as well as the relationship instances we need for this.
219228 $ foreignKey = $ foreignKey ?: $ this ->getForeignKey () . 's ' ;
220229
221230 $ instance = new $ related ;
222-
231+
223232 $ otherKey = $ otherKey ?: $ instance ->getForeignKey () . 's ' ;
233+
224234 // If no table name was provided, we can guess it by concatenating the two
225235 // models using underscores in alphabetical order. The two model names
226236 // are transformed to snake case from their default CamelCase also.
227237 if (is_null ($ collection ))
228238 {
229- $ collection = snake_case ( str_plural ( class_basename ( $ related )) );
239+ $ collection = $ instance -> getTable ( );
230240 }
231241
232242 // Now we're ready to create a new query builder for the related model and
233243 // the relationship instances for the relation. The relations will set
234244 // appropriate query constraint and entirely manages the hydrations.
235245 $ query = $ instance ->newQuery ();
236246
237- return new BelongsToMany ($ query , $ this , $ collection , $ foreignKey , $ otherKey , $ caller [ ' function ' ] );
247+ return new BelongsToMany ($ query , $ this , $ collection , $ foreignKey , $ otherKey , $ relation );
238248 }
239249
240250 /**
@@ -312,4 +322,4 @@ public function __call($method, $parameters)
312322 return parent ::__call ($ method , $ parameters );
313323 }
314324
315- }
325+ }
0 commit comments