user3274489
user3274489

Reputation: 304

Correct way to set up this Laravel relationship?

I'm after a bit of logic advice. I am creating a system where users login and register their participation at an activity. They can participate at an activity many times. What is the best way to do this? I want to ensure I can use eloquent with this rather than creating my own functions.

I am imagining...

Users:

id

Activitys:

id
name

Participations:

id
user_id
activity_id
time_at_activity

I want to later be able to do such things as: $user->participations->where('activity_id', 3) for example.

What is the best way to set this up? I had in mind..

User: hasMany->Participations

Activity: belongsTo->Participation

Participation: hasMany->Activitys & belongsTo->User

Does this look correct?

Upvotes: 0

Views: 177

Answers (3)

Foued MOUSSI
Foued MOUSSI

Reputation: 4813

DB schema enter image description here

// App\User
public function participations()
{
    return $this->hasMany('App\Participation');
} 
// You may create App\Participation Model
// App\Participation 
public function user()
{
    return $this->belongsTo('App\User');
} 

// Controller
$userParticipations = $user->participations->where('activity_id', 3);
// eager loading version
$userWithParticipations = $user->with(['participations' => function($q) { $q->where('activity_id', 3) }])->get();

Upvotes: 1

voxelhog
voxelhog

Reputation: 71

enter image description hereThe users schema can relate to activities through a pivot table called participations:

/**
 * Indicate that the model belongs to a user.
 *
 * @see \App\Model\User
 *
 * @return BelongsTo
 */
public function user()
{
    return $this->belongsTo(User::class);
}

/**
 * Indicate that the model belongs to many activity participations.
 *
 * @see \App\Model\Activity
 *
 * @return BelongsTo
 */
public function participations()
{
    return $this->belongsToMany(Activity::class, 'participations');
}

$user->participations()->attach($activity);

You may want to add the reciprocal relationships. These can be separated out into traits for code reuse. ->attach(['participated_at' => now()])

Upvotes: 2

Arun A S
Arun A S

Reputation: 7006

You can use Many-to-Many Relationship.

Use Participation as your pivot table. Define relationships as

/* in User */
public function activity()
{
    return $this->belongsToMany('App\Models\Activitys','participation','user_id','activity_id')->as('participation')->withPivot('time_at_activity');
} 

/* in Activity */
public function user()
{
    return $this->belongsToMany('App\Models\Users','participation','activity_id','user_id')->as('participation')->withPivot('time_at_activity');
} 

Upvotes: 1

Related Questions