@@ -201,40 +201,50 @@ public function belongsTo($related, $foreignKey = null, $otherKey = null, $relat
201
201
}
202
202
203
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 )
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 )
213
214
{
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
+
216
225
// First, we'll need to determine the foreign key and "other key" for the
217
226
// relationship. Once we have determined the keys we'll make the query
218
227
// instances as well as the relationship instances we need for this.
219
228
$ foreignKey = $ foreignKey ?: $ this ->getForeignKey () . 's ' ;
220
229
221
230
$ instance = new $ related ;
222
-
231
+
223
232
$ otherKey = $ otherKey ?: $ instance ->getForeignKey () . 's ' ;
233
+
224
234
// If no table name was provided, we can guess it by concatenating the two
225
235
// models using underscores in alphabetical order. The two model names
226
236
// are transformed to snake case from their default CamelCase also.
227
237
if (is_null ($ collection ))
228
238
{
229
- $ collection = snake_case ( str_plural ( class_basename ( $ related )) );
239
+ $ collection = $ instance -> getTable ( );
230
240
}
231
241
232
242
// Now we're ready to create a new query builder for the related model and
233
243
// the relationship instances for the relation. The relations will set
234
244
// appropriate query constraint and entirely manages the hydrations.
235
245
$ query = $ instance ->newQuery ();
236
246
237
- return new BelongsToMany ($ query , $ this , $ collection , $ foreignKey , $ otherKey , $ caller [ ' function ' ] );
247
+ return new BelongsToMany ($ query , $ this , $ collection , $ foreignKey , $ otherKey , $ relation );
238
248
}
239
249
240
250
/**
@@ -312,4 +322,4 @@ public function __call($method, $parameters)
312
322
return parent ::__call ($ method , $ parameters );
313
323
}
314
324
315
- }
325
+ }
0 commit comments