首页 > 解决方案 > SQLSTATE [42S22]:找不到列:1054 'where 子句为什么'中的未知列'4'我找不到错误

问题描述

我在我的 php/laravel 代码中有一个 select wuery 问题是当我运行它时它给出了这个错误

 SQLSTATE[42S22]: Column not found: 1054 Unknown column '4' in 'where clause'
where (`element_value`.`p_id` = `4`))

这是我的查询

DB::table('value_tbl')
    ->select(DB::raw("CONCAT(values.value_name,'/',element_value.qan) AS full_value"))
    ->leftJoin('element_value','element_value.element_id','value.element_id')
    ->where (['element_value.p_id'=>$a->p_id])->get()->pluck('full_value')->toArray())

标签: phpsqllaravel

解决方案


如果要使用运算符, where 函数需要三个参数:第一个是列名,第二个是运算符,第三个是要比较的值。

将您的条件更改为如下所示

->where('element_value.p_id', '=', $a->p_id)
// or, because you are making an exact match, do this
->where('element_value.p_id', $a->p_id)

你现在的代码很困惑,因为你告诉 Laravel 你正在通过使用数组作为 where 第一个参数来创建多个 where 条件。
然后,Laravel 获取该数组的值并尝试将其转换为列、运算符和值——就像它对上述代码片段所做的那样。

如果您真的想使用数组,则需要执行以下操作:

->where([
    ['element_value.p_id', '=', $a->p_id]
])
// or, because you are making an exact match, do this
->where([
    ['element_value.p_id', $a->p_id]
])

注意我们是如何传递两组数组的?
这是因为 Laravel 要么希望每个参数分开,要么希望一个包含正确签名的数组数组。


如需更详细的答案;签名看起来像这样

public function where($column, $operator = null, $value = null, $boolean = 'and')

如果$column是一个数组,则假定将一个数组数组传递给该方法,并且每个子数组将有效地分布在上述签名中。

当您将单个数组传递给该方法时,Laravel 正在获取 的值,4然后将其用作$column.
这是因为您为该数组使用了键值,因此您使用的列名实际上被忽略了。

这个方法的另一个有趣的地方是它有以下代码片段

// If the given operator is not found in the list of valid operators we will
// assume that the developer is just short-cutting the '=' operators and
// we will set the operators to '=' and set the values appropriately.
if ($this->invalidOperator($operator)) {
    [$value, $operator] = [$operator, '='];
}

这允许我们不传入运算符,Laravel 将假设我们希望使用 an=来代替。
这就是我能够从上面的示例中省略它的方式。


推荐阅读