Laravel对相关模型领域进行雄辩的搜索 [英] Laravel eloquent search on fields of related model

查看:82
本文介绍了Laravel对相关模型领域进行雄辩的搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个雄辩的模型,

用户:用户(ID,用户名,密码,电子邮件,状态)

个人资料:个人资料(ID,用户名,名字,姓氏,性别,出生日期)

在控制器逻辑中,我热切地加载Profile模型.

In the controller logic, I am eagerly loading the Profile model.

我可以做到

$user = User::with('Profile')->get();

$user = User::with('Profile')->where('status', '1')->get();

但是如何做类似的事情

$user = User::with('Profile')->where('status', '1')->where('gender', 'Male')->get();

推荐答案

这是whereHas派上用场的地方:

$user = User::with('Profile')->where('status', 1)->whereHas('Profile', function($q){
    $q->where('gender', 'Male');
})->get();

基本上,它添加了用户需要具有gender = Male

Basically it adds the condition that the user needs to have a profile with gender = Male

这篇关于Laravel对相关模型领域进行雄辩的搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆