3 回答

TA貢獻1880條經驗 獲得超4個贊
用戶架構可以通過稱為參與的數據透視表與活動相關聯:
/**
* 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()])

TA貢獻1794條經驗 獲得超7個贊
數據庫架構
// 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();

TA貢獻1850條經驗 獲得超11個贊
您可以使用多對多關系。
用作數據透視表。將關系定義為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');
}
- 3 回答
- 0 關注
- 119 瀏覽
添加回答
舉報