【问题标题】:Laravel with where like condition in relationshipLaravel 在关系中具有类似条件
【发布时间】:2020-10-24 18:54:16
【问题描述】:

我有一个具有以下关系的 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);
}

【问题讨论】:

  • 你能解释一下你想在这里实现什么吗?
  • 我有两个具有上述关系的表,WorkPackage 表有 'title'、'project_id' 和 work_items 表有 'title'、'work_package_id' 列。现在我想用两个表的标题列匹配的两个表搜索关键字。

标签: laravel relationship eloquent-relationship


【解决方案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;

【讨论】:

  • 你需要 () 在 workPackage 之后为关系而不是对象,$this->workPackage()->whereHas
  • @OMR 你怎么知道的?原来的问题没有,我们也不知道$this存在的上下文
  • @STA 当我使用 whereHas 时它返回空数据,当我使用 with 时,至少获得具有匹配记录的 WorkPackage 表数据。一个问题是我无法在 $query->where('title', 'LIKE', "%{$title}%"); 中使用 $title获取未定义的标题时出错。
  • @Tushar $this->workPackage()->whereHas 怎么样?
  • @STA $this-> workPackage 只能工作 workPackage() 这不起作用,因为我已经为它创建了对象
【解决方案2】:

以下代码对我有用。感谢大家帮助得到正确答案。

   $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;

【讨论】:

  • 你加use ($title)?
【解决方案3】:

我认为你的问题将通过 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();

【讨论】:

    猜你喜欢
    • 2021-03-10
    • 2019-10-12
    • 2018-11-25
    • 1970-01-01
    • 2014-11-30
    • 1970-01-01
    • 2021-10-19
    • 2021-10-09
    • 2023-03-19
    相关资源
    最近更新 更多