繁体   English   中英

检索与laravel模型查询匹配的条件

[英]Retrieve conditions matched on laravel model query

这可能是一个SQL限制,但是我正在研究Laravel项目,所以我提出了一些问题来解决我要完成的任务。

我正在执行对模型的搜索(及其关系)

Auth::user()->employers()
    ->where('name', 'like' $filter)
    ->orWhereHas('locations.location', function($query) use ($filter) {
        $query->where('name', 'like', $filter);
    })
    ->orWhereHas('locations.branches', function($query) use ($filter) {
        $query->where('name', 'like', $filter);
    })
    ->orWhereHas('locations.positions', function($query) use ($filter) {
        $query->where('name', 'like', $filter);
    })->get();

我希望能够识别出与记录匹配的条件中的哪一个,以便我可以告诉前端,“嘿,此记录正在显示给您,因为嵌套在其中的x属性与您的搜索条件匹配。” 其中x是使其匹配的条件。

上面的代码返回匹配记录的集合。 我想知道这些记录的每条记录在哪里匹配。

如果我正确理解了您的问题,则只想显示您的模型并说“您正在看到它是因为...”。 如果确实如此,并且查询完成后模型可能仅具有位置,分支或位置,那么您可以简单地在if语句中查询它。 假设您的“搜索”条件为$name

$matches = array();

if($user->location == $name) {
  array_push($matches, 'location');
};
if($user->branch == $name) {
  array_push($matches, 'branch');
};
if($user->position == $name) {
  array_push($matches, 'position');
};

return $matches;

您基本上已经完成了查询,现在只需检查参数满足条件的对象即可。 如果有很多困难条件,尽管我会寻找一种更加面向对象的方法,但是在这种情况下,对对象使用简单的过程方法就可以了。 如果有多个,则可以在User模型上返回具有匹配值的数组:

public function foundBy($name) {

    $matches = array();

    if($this->location == $name) {
      array_push($matches, 'location');
    };
    if($this->branch == $name) {
      array_push($matches, 'branch');
    };
    if($this->position == $name) {
      array_push($matches, 'position');
    };
    return $matches;

}

这样称呼它:

$foundBy = $user->foundBy($name);

并且应该返回一个数组。

这样,方法返回的内容将通过查看数组中的值来告诉您对象如何匹配。

希望这对您有所帮助!

现在,您的查询如下所示:

select *
from employees
where name like ?
  or exists (select * from locations ...)
  or exists (...)

将子查询添加到SELECT部分时,将获得布尔值:

select *,
  exists (select * from locations ...) as hasLocations
  exists (...) as hasBranches
  ...
from employees
where name like ?
  or exists (select * from locations ...)
  or exists (...)

您必须查看whereHas实现,以找到一种从关系生成这些子查询的方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM