我有一个这样的查询,我不确定如何为每个表的选择列添加别名。你能帮我吗?
$columns = array_merge(json_decode($data->columns), json_decode($data->columns2));
$result = DB::table($data->type)
->select($columns)
->join('tabs', 'data.id', '=', 'tabs.id')
->get();
要回答您的问题,您可以像在 SQL 中一样添加
AS newColumnName
:
->select(['name AS title', 'email AS emailAddress'])
.
此外,您真的不想像这样将未经清理的表名和列名传递给您的查询。它们没有被 Laravel 清理,是一个潜在的漏洞。更多信息可以在标注框中找到:https://laravel.com/docs/8.x/queries#where-clauses
从评论中我得出结论,您想要从
$data->columns
中选择列,并为它们添加别名,就像它们在 $data->columns2
中一样。我都不知道两者的数据结构,但我认为你的意思是这样的:
$select = array_map(
function($column, $alias) {
return "{$column} AS {$alias}";
},
$data->columns,
$data->columns2
);
var_dump($select);
这是一个沙箱:http://sandbox.onlinephpfunctions.com/code/12487b8f2d590aa9f0d7a6cb0d7d4f1f067b4cb0