Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/231.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/56.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php Laravel雄辩关系自定义查询_Php_Mysql_Laravel_Eloquent_Entity Relationship - Fatal编程技术网

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();