我有一个具有以下关系的WorkPackage模型。
public function work_items()
{
return $this->hasMany(WorkItem::class);
}
WorkPackage具有“标题”,“ project_id”列,而work_items具有“标题”,“ 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);
}
答案 0 :(得分:1)
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;
答案 1 :(得分:0)
以下代码对我有用。感谢大家的帮助,以得到正确的答案。
$result['data'] = $this->workPackage->with(['work_items' => function ($q) use ($title) {
$q->where('title', 'LIKE', "%{$title}%");
}])
->where('project_id', $projectId)
->where('title', 'LIKE', "%{$title}%")
->get();
return $result;
答案 2 :(得分:0)
我认为您的问题将通过join方法解决:
$result = $this->workPackage
->join('work_items', 'work_packages.id', '=', 'work_items.package_id')
->where('work_items.title', 'LIKE', '%{$term}%')
->orWhere('work_packages.title', 'LIKE', '%{$term}%')
->get();