I have a query like this where I am not sure how to alias the select columns for each table. Could you help me with that?
$columns = array_merge(json_decode($data->columns), json_decode($data->columns2));
$result = DB::table($data->type)
->select($columns)
->join('tabs', 'data.id', '=', 'tabs.app_bundles_id')
->get();
CodePudding user response:
To answer your question, you add AS newColumnName
as you would in SQL:
->select(['name AS title', 'email AS emailAddress'])
.
Additionally, you really really don't want to pass table names and column names unsanitized to your query like this. They are NOT sanitized by Laravel and are a potential vulnerability. More info can be found in the callout box at https://laravel.com/docs/8.x/queries#where-clauses
From the comments I concluded you want to select the columns from $data->columns
and alias them like they're in $data->columns2
. I don't know the data structure for neither, but I think you mean something like this:
$select = array_map(
function($column, $alias) {
return "{$column} AS {$alias}";
},
$data->columns,
$data->columns2
);
var_dump($select);
Here's a sandbox: http://sandbox.onlinephpfunctions.com/code/12487b8f2d590aa9f0d7a6cb0d7d4f1f067b4cb0