首页 > 解决方案 > 如何检查表是否已经在 Laravel Query Builder 中有 where 子句?

问题描述

是一个示例,说明我们如何检测表是否已加入 Laravel 的查询中。

public static function isJoined($query, $table)
    {
        $joins = $query->getQuery()->joins;
        if($joins == null) {
            return false;
        }

        foreach ($joins as $join) {
            if ($join->table == $table) {
                return true;
            }
        }

        return false;
    }

我需要的是提取where查询中的子句。

我有一个具有join一些where条件的查询,我需要where在嵌套选择中使用其中一个条件。

现在我需要从查询中提取 where 子句并再次使用它。问题是如何确定我的查询是否包含我的 Eloquent 查询where中表的特定列(例如)的任何条件?org.id

我试图wheres从查询中提取如下,但不像我们所拥有的连接

$wheres = $query->getQuery()->wheres;
  foreach ($wheres as $where) {
    dd(array_keys($where));
  }

我收到的是:

array:3 [
  0 => "type"
  1 => "query"
  2 => "boolean"
]

的值typenested,如果我尝试以下代码:

$wheres = $query->getQuery()->wheres;
  foreach ($wheres as $where) {
     dd($where['query']->wheres);
  }

然后我有:

array:1 [
  0 => array:5 [
    "type" => "Basic"
    "column" => "org.path"
    "operator" => "LIKE"
    "value" => "/202001/10000000/12400000%"
    "boolean" => "and"
  ]
]

现在为什么第一个wheres返回不同的对象?我首先想到了这个结果$where

标签: phplaraveleloquent

解决方案


->wheres您可以对查询生成器的属性执行几乎相同的操作。它将包含以下格式的 where 子句数组:

    ["type"] => string(5) "Basic"
    ["column"] =>string(1) "q"
    ["operator"] => string(1) "="
    ["value"] => int(2)
    ["boolean"] => string(3) "and"

由此看来,您可以使用column属性。

UPD:基本上你可以创建一个递归函数来检查它:

  ...
  $wheres = $query->getQuery()->wheres;
  foreach ($wheres as $where) {
     if( $checkColumn($where, 'myColumn) ) { 
        // found it
        break;
     }
  }

  function checkColumn($where, $column) {
     if( $where['type'] == 'nested' ) {
         return checkColumn($where['query'], $column);
     }
     else {
        return $where['column'] == $column;
    }
  }

推荐阅读