Laravel查询拼接字段时出现SQL字段不存在报错问题
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:
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"; } }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

