建立这种Laravel关系的正确方法?

问题描述 投票:0回答:3

我有一些逻辑建议。我正在创建一个系统,用户可以在该系统上登录并注册他们在活动中的参与。他们可以多次参加活动。做这个的最好方式是什么?我想确保自己可以用雄辩的语言,而不是创建自己的函数。

我在想...

用户:

id

活动:

id
name

参加:

id
user_id
activity_id
time_at_activity

我希望以后能够执行以下操作:$user->participations->where('activity_id', 3)例如。

设置此设置的最佳方法是什么?我想到了..

用户:hasMany->参与人数

活动:belongsTo->参与

参与:hasMany->活动和belongsTo->用户

看起来正确吗?

php laravel laravel-5 php-7 laravel-6
3个回答
2
投票

[enter image description here用户架构可以通过称为参与的数据透视表与活动相关:

/**
 * 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);

您可能想添加相互关系。这些可以分为特征以供代码重用。 ->attach(['participated_at' => now()])


1
投票

您可以使用Many-to-Many关系。

使用Participation作为数据透视表。将关系定义为

/* 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');
} 

1
投票

数据库模式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();
© www.soinside.com 2019 - 2024. All rights reserved.