I have two multi-word models, let's call them FunkyModel
and AnotherModel
.
Will creating a pivot table named another_model_funky_model
work?
The docs and examples I've come across all use single word model names like this: model A - User
, model B - Address
, and pivot table will then be address_user
.
CodePudding user response:
If you dive into the source code of the BelongsToMany
relation function, you'll find that if you haven't provided a $table
, the code will execute the function joiningTable
. This uses the current model and the passed related class, snake cases the names and then puts them in alphabetical order of each other.
Simply said, no matter if you have a single word or a couple, the result will always be the 2 classes snaked, in alphabetical order. Note that the alphabetical order is applied by the default php sort.
Examples:
- Department Occupation >
department_occupation
- AwesomeModel LessInterestingModel >
awesome_model_less_interesting_model
- Role UserPermission >
role_user_permission
You can even try and see what the auto-generated name is by simply calling the following:
(new Model)->joiningTable(OtherModel::class, (new OtherModel));
CodePudding user response:
Yes it would work, you can also name it whatever you want, you just need to declare the table name in the relation (same goes for the foreign keys)
class FunkyModel
{
public function anotherModels()
{
return $this->belongsToMany(AnotherModel::class, 'pivot_table_name', 'funky_model_id', 'another_model_id');
}