Reputation: 1637
I have two master tables. i.e, users
and tasks
. Primary key column names are in_user_id
for users table and in_task_id
for tasks table.
There is relational table users_tasks
(to see a task are assigned to which users and a user is assigned with which tasks). Foreign key columns are in_task_id
and in_worker_id
in users_tasks table.
I want to define relationship of users and tasks (many-to-many) into both models. I have read this doc. But in my case, primary key column is in_user_id in users table. But foreign key column name is in_worker_id in users_tasks table.
So I don't know that how to handle fourth parameter in relationship function (return $this->belongsToMany('App\User', 'users_tasks', 'in_task_id', ?);
in Task Model file). Either in_user_id
or in_worker_id
or something need to define more. If anyone knows the solution, it will be appreciated.
Upvotes: 1
Views: 771
Reputation: 40653
From laravel eloquent documentation on many-to-many relationships
In addition to customizing the name of the joining table, you may also customize the column names of the keys on the table by passing additional arguments to the belongsToMany method. The third argument is the foreign key name of the model on which you are defining the relationship, while the fourth argument is the foreign key name of the model that you are joining to:
In your case it would be :
return $this->belongsToMany('App\User', 'users_tasks', 'in_task_id', 'in_worker_id');
Now this assumes a few things:
users_tasks
) also needs it's own identifier column, typically an auto-incremented id.Upvotes: 1
Reputation: 1101
Try this
$this->belongsToMany('App\User, 'users_tasks', 'in_worker_id ', 'in_user_id ');
params -> model, relation table, foreignkey, primary key
And also relation tables should be in the alphabetical order. (best way) It must be tasks_users
Upvotes: 1