首页 > 解决方案 > 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);
}

标签: laravelrelationshipeloquent-relationship

解决方案


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;

推荐阅读