编程语言
首页 > 编程语言> > php-Laravel雄辩的关系自定义查询

php-Laravel雄辩的关系自定义查询

作者:互联网

我有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,已完成

最终值只能在0到1之间.

现在我知道,当我要选择用户学习的所有主题时,我必须编写$user->主题.

但是,如果我想选择用户学习的所有主题并且数据透视表中的最终值等于1怎么办?

解决方法:

您需要在关系定义中添加“ 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();

标签:entity-relationship,laravel,eloquent,mysql,php
来源: https://codeday.me/bug/20191119/2035899.html