Laravel many-to-many relationship query

血红的双手。 提交于 2019-12-25 00:52:05

问题


I am building a Laravel application with a users table and an activities table, and a many-to-many relationship between activities and users implemented with a pivot table called assignments:

  • users: id, ...
  • activities: id, ...
  • assignments: id, activity_id, user_id, ...

I need to keep a record of each time a user completes an activity. A user can complete the same activity many times. I am trying to decide on the best way to model this in the database. The options as far as I can see are:

  1. a table completions: id, assignment_id, ...
  2. a second pivot table completions: id, activity_id, user_id, ...

I can create the migrations etc. However I am struggling with the Model classes and their relationship methods. In particular, for the first option above, how would I define the required Model classes and relationship methods?


回答1:


Well, you have pretty much everything sorted except the activity tracking. So, here's what I propose:

users table

with columns id, name, email, etc

activities table

with columns id, name, etc

user_activity table (pivot)

with columns id, user_id, activity_id, etc This table will contain the many to many mapping between users and activities.

activity_tracking

with columns id, user_activity_id, status, updated_at etc Here you could use an integer value for status to signify completion lets say 1. And using updated_at and created_at you could track activity start and completion timing.




回答2:


create activity_user table and just add activity_id and user_id. id column unnecessary for this. Then add this codes to User Model:

public function activity()
{
    return $this->belongsToMany('App\Activity', 'activity_user', 'user_id', 'activity_id');
}

If i understand correctly, there is no need anything else.



来源:https://stackoverflow.com/questions/50487508/laravel-many-to-many-relationship-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!