我的数据库中有默认的laravel users
表和自定义的educations
表。在educations
表中,用户可以保存教育历史记录。
示例educations
数据:
------------------------------------------------------------
id | user_id | university | speciality | finish_year | level
------------------------------------------------------------
1 | 16 | Boston | Developer | 2018 | 4
------------------------------------------------------------
2 | 10 | Sinergy | Designer | 2014 | 4
------------------------------------------------------------
9 | 16 | Sinergy | Economist | 2010 | 8
------------------------------------------------------------
现在,我如何才能让用户使用拉拉雄辩的教育水平?
例如,获得教育级别== 4的用户
发布于 2018-11-27 12:46:46
考虑到用户模型中有一个表示educations
关联的HasMany
方法,您可以使用雄辩的has
(或whereHas
)方法:
$users = App\User::whereHas('educations', function ($query) {
$query->where('level', 4);
})->get();
这是到文档的链接。
发布于 2018-11-27 10:25:43
如果您的关系设置正确,那么在您的User
模型中应该有如下内容:
public function educations() {
return $this->hasMany(Education::class);
}
然后,简单的使用如下:
User::with(['educations' => function($query) {
$query->where('level', 4);
}])->get()->filter(function($user) {
return $user->educations->count() > 0;
});
相反的办法是:
Education::with('user')->where('level', 4)->get();
这将给出级别为4的教育的列表,以及分配给它的每个用户。
https://stackoverflow.com/questions/53497455
复制相似问题