Php Laravel雄辩关系自定义查询
我有两个表:Php Laravel雄辩关系自定义查询,php,mysql,laravel,eloquent,entity-relationship,Php,Mysql,Laravel,Eloquent,Entity Relationship,我有两个表:用户和主题 用户和主题之间的关系是多对多的。 在User.php和Subject.php模型中,我定义了: User.php function subjects() { return $this->belongsToMany('App\User'); } Subject.php function users() { return $this->belongsToMany('App\Subject'); } 透视表是subject\u user,它有3列: 主题id,用
用户
和主题
用户
和主题
之间的关系是多对多的。
在User.php和Subject.php模型中,我定义了:
User.php
function subjects() { return $this->belongsToMany('App\User'); }
Subject.php
function users() { return $this->belongsToMany('App\Subject'); }
透视表是subject\u user
,它有3列:
主题id
,用户id
,完成
finished
值只能介于0和1之间
现在我知道,当我想要选择用户学习的所有主题时,我必须编写$user->subjects
但是,如果我想选择用户学习的所有主题,并且pivot表中的finished值等于1,该怎么办?您需要立即加载该关系并使用
wherePivot
方法
$user = User::with(['subjects' => function($q) {
$q->wherePivot('finished', 1);
}])->fine($user_id);
您需要在关系定义中添加“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();