laravel - Laravel 在关系中具有类似条件
问题描述
我有一个具有以下关系的 WorkPackage 模型。
public function work_items()
{
return $this->hasMany(WorkItem::class);
}
WorkPackage 有 'title','project_id' 列,work_items 有 'title','work_package_id' 列。现在我想搜索用户输入的关键字与两个表中的标题匹配。
这是我尝试过的功能
public function getWorkPackageProposals($projectId, $title)
{
$result['data'] = $this->workPackage->with(['work_items' => function ($query) {
$query->where('title', 'LIKE', "%{$title}%");
}])
->where('project_id', $projectId)
->where('title', 'LIKE', "%{$title}%")
->get();
return $result;
}
但它不工作。请找到以下我用来创建 WorkPackage 对象的代码。
public function __construct(WorkPackage $workPackage)
{
$this->workPackage = $workPackage;
$this->setModel(WorkPackage::class);
$this->workItemRepository = app(WorkItemRepository::class);
}
解决方案
whereHas()
为相关模型指定额外的过滤器以检查:
$result['data'] = $this->workPackage->whereHas('work_items', function ($query) use ($title) {
$query->where('title', 'LIKE', "%{$title}%");
})
->where('project_id', $projectId)
->where('title', 'LIKE', "%{$title}%")
->get();
return $result;
推荐阅读
- mongodb - 按记录之间的时间差分组在一起
- r - 如何从 bsts R 包中提取包含概率
- javascript - 反应本机异步存储不起作用
- spring-boot - 如何让 JavaMailSender 在错误的邮件密码上加载应用程序上下文时不会失败?
- jenkins - 获取 Groovy 脚本名称
- dart - 如何在 BottomNavigationBarItem 上方对齐小部件?
- node.js - Request.post 等待它结束 NodeJS
- html - Flexbox 更改响应顺序
- swift - Corebluetooth - 扫描特定 CBUUID 不起作用
- c - 构建 #define 指令数组