尝试在Laravel上使用DB::raw
查询时遇到了一个问题。当我尝试遍历结果集时,我无法定位某个列,因为它的名称包含空格:
$result = DB::connection("example")->select(DB::raw(
"SELECT table.column_1 AS 'NameOne',
table.column_2 AS 'Name Two'
FROM example;"
));
如您所见,NameOne
不包含空格,但Name Two
包含空格。循环遍历结果集时,我无法回显table.column_2 AS 'Name Two
的结果,因为我无法正确定位它。我尝试了什么:
<!-- language: html -->
@foreach($result AS $item)
<tr>
<td>{!! $result->NameOne !!}</td> <!-- Works Fine -->
<td>{!! $result->Name Two !!}</td> <!-- Doesn't work (obvious syntax error) -->
<td>{!! $result->Name_Two !!}</td> <!-- Doesn't work (undefined property) -->
<td>{!! $result->Name+Two !!}</td> <!-- Doesn't work (undefined property) -->
<td>{!! $result->NameTwo !!}</td> <!-- Doesn't work (undefined property) -->
</tr>
@endforeach
具体来说,未定义的属性错误是:
未定义属性:stdClass :: $ Name_Two(查看:/var/www/html/APPNAME/resources/views/index.blade.php)
我不想更改密钥,因为这些结果正在导出到Excel,我想保留列名称。记住这一点,我将如何回应这些结果?
此外,dd($results)
的输出:
array:1 [▼
0 => {#179 ▼
+"NameOne": "NameOne"
+"Name Two": "NameTwo"
}
]
答案 0 :(得分:6)
您可以使用
<td>{!! $result->{'Name Two'} !!}</td>
答案 1 :(得分:0)