Laravel Eloquent 关系自定义查询
Laravel Eloquent Relationship custom query
我有 2 个 table: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'); }
主元 table 是 subject_user
,它有 3 列:
subject_id
、user_id
、finished
finished
值只能在 0 到 1 之间。
现在我知道,当我想 select 一个用户学习的所有科目时,我必须写 $user->subjects
。
但是如果我想 select 一个用户学习的所有科目并且数据透视表中的完成值 table 等于 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();
我有 2 个 table: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'); }
主元 table 是 subject_user
,它有 3 列:
subject_id
、user_id
、finished
finished
值只能在 0 到 1 之间。
现在我知道,当我想 select 一个用户学习的所有科目时,我必须写 $user->subjects
。
但是如果我想 select 一个用户学习的所有科目并且数据透视表中的完成值 table 等于 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();