You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel查询拼接字段时出现SQL字段不存在报错问题

Fixing "Unknown column" Error When Adding Selected Fields from External Array in Laravel

Got it, let's break down why you're hitting that SQL error and fix it right away.

What's Causing the Issue?

Your current code builds a single string with all your selected fields, then passes that string wrapped in an array to addSelect(). Laravel interprets this entire string as one single column name instead of splitting it into separate fields. That's why you see the error about stmd_adminusers.id, CONCAT(firstName, ' ', lastName) being an unknown column—it's treating the whole thing as a single column identifier.

The Correct Fix

Instead of concatenating fields into a single string, collect each desired field as a separate element in an array. Laravel's addSelect() accepts an array of individual field expressions, which it will parse correctly.

Here's how to rewrite your code:

  1. Build an array of select fields

    $selectFields = [];
    foreach($param as $key => $val){
        if($val == 'userId'){
            $selectFields[] = "adminusers.id";
        }
        if($val == 'name'){
            $selectFields[] = "CONCAT(firstName, ' ', lastName) as name";
        }
    }
    
  2. Pass the array directly to addSelect()

    $where = '1';
    $resultSet = UserAdmin::whereRaw($where)
        ->addSelect($selectFields)
        ->groupBy('adminusers.id');
    

Why This Works

By using an array, each entry is treated as a distinct field or expression. Laravel will automatically format these into the correct SQL SELECT clause without misinterpreting the whole thing as a single column. This also eliminates the trailing comma issue from your original string concatenation—no more worrying about extra commas breaking your query!

内容的提问来源于stack exchange,提问作者Niladri Banerjee - Uttarpara

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 03:58:45