【问题标题】:Search both parent and child titles and return results based on either match搜索父标题和子标题并根据任一匹配返回结果
【发布时间】:2021-11-20 20:04:13
【问题描述】:

我怎样才能让它搜索projects.titleitems.title 并且如果它只匹配其中一个,仍然返回结果?现在如果它匹配一个项目,它不会显示,除非它也匹配一个项目标题,反之亦然。我明白为什么,但我可能不能急于做我需要做的事吗?

$query = Auth::user()->projects()->where('projects.title', 'LIKE', "%$this->search%");

$query->with(['items' => function ($query) {
    $query->where('items.title', 'LIKE', "%$this->search%");
    $query->with('tags');
}]);

$query->get();

我想我需要类似“如果它匹配一个或多个项目标题,返回过滤的项目和相关项目。如果它只匹配项目标题,返回项目和所有相关项目”。想法?

让它与以下内容一起工作(以及 with 部分的类似查询):

$user->projects()->with('items')->where(function($query){
  $query->where('title', 'like', '...')->orWhereHas('items', function($query){
    $query->where('title', 'like', '...');
  });
});

【问题讨论】:

    标签: php laravel database eloquent


    【解决方案1】:

    将条件移至闭包:

    $data = Auth::user()
                ->projects()
                ->with(['items' => function ($query) {
                    $query
                        ->where('projects.title', 'LIKE', "%$this->search%")
                        ->orWhere('items.title', 'LIKE', "%$this->search%")
                        ->with('tags');
                }])->get();
    

    【讨论】:

    • 谢谢!我想我试过了,它无法从 with 函数内部看到项目。我会再试一次。
    猜你喜欢
    • 2016-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多