blackbird
blackbird

Reputation: 3

Laravel many-to-many relationship query

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:

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?

Upvotes: 0

Views: 324

Answers (2)

Ali Özen
Ali Özen

Reputation: 1609

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.

Upvotes: 0

Aman
Aman

Reputation: 449

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.

Upvotes: 1

Related Questions