laravel - 如何在laravel中搜索hasMany关系
问题描述
我有公司和药房的模型
<?php
// Company.php
public function dispensary()
{
return $this->hasMany(Dispensary::class);
}
// Dispensary.php
public function company()
{
return $this->belongsTo(Company::class);
}
我想要的是首先获得用户所属公司的药房。
$auth = \Auth::user();
$userCompany = $auth->company()->get();
$dispensaries = Company::find($userCompany->first()->id)->dispensary;
我应该如何构造一个查询,用户可以在其中搜索用户所属的药房列表。
我试过使用 whereHas 但它是从公司而不是药房搜索
Company::find($userCompany->first()->id)
->whereHas('dispensary', function ($query) use ($name) {
$query->where('name', 'like', "%{$name}%");
})->get();
解决方案
好的,我终于通过使用 where 子句让它工作了
$company = Company::find($id)->dispensary()
->where('name', 'like', "%{$name}%")
->where('contact_email', 'like', "%{$email}%")
->get();
推荐阅读
- javascript - 如何修复 ClearInterval
- python - AttributeError: 'guiCreate' 对象没有属性 'master' - 为什么我不能访问另一个类的函数?
- jdbc - ORA-12518 TNS:listener 无法从 JBOSS 6,X 的数据源中切换客户端连接
- javascript - 加载的 HTML 内容未显示在 CKEDITOR 文本区域中
- bash - 如何匹配shellscript中的特定文件扩展名
- sql - 错误的 SQL 语法;')' 附近的语法不正确
- vb.net - 随机数之和必须大于 x 且小于 y
- c# - 当 ASP.NET Core 2.2 项目出现特定异常时,如何重定向用户?
- sql - SQL Server 中的 CTE 查询:结果中存在一行时退出
- c# - PDF转base64转换器和查看base64