我有2个表:USERS
和SUBJECTS
USER
和SUBJECT
之间的关系很多。
在User.php和Subject.php模型中,我定义了:
user.php的
function subjects() { return $this->belongsToMany('App\User'); }
Subject.php
function users() { return $this->belongsToMany('App\Subject'); }
数据透视表是subject_user
,它有3列:
subject_id
,user_id
,finished
finished
值只能介于0和1之间。
现在我知道当我想选择用户研究的所有主题时,我必须写$user->subjects
。
但是,如果我想选择用户研究的所有主题并且数据透视表中的完成值等于1,该怎么办?
答案 0 :(得分:4)
你需要添加" withPivot()"你的关系定义,如下:
function subjects() { return $this->belongsToMany('App\User')->withPivot('finished'); }
function users() { return $this->belongsToMany('App\Subject')->withPivot('finished'); }
然后你可以这样做:
$user->subjects()->where('finished', 1)->get();
答案 1 :(得分:-1)
您需要急切加载该关系并使用$user = User::with(['subjects' => function($q) {
$q->wherePivot('finished', 1);
}])->fine($user_id);
方法。
{{1}}