简体   繁体   中英

how to define many to many relationship in laravel models?

I have two master tables. ie, 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.

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

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:

  1. Your user and task model are working properly (since you have non-conventional identifiers you've defined them in your models).
  2. Not sure if its still the case but in previous versions of Laravel, your pivot table (in this case users_tasks ) also needs it's own identifier column, typically an auto-incremented id.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM