Zbigniew Kisły
Zbigniew Kisły

Reputation: 742

Query builder object doesn't see aliases in previously built object (Laravel)

Here's my first query:

$base=\DB::table('user')->select('firstname as name');

and then I want to access aliased column in second query:

$base->select('name');

but I see error. I can access all columns from table user though. Is there a way to change it so I can use aliased name in the second query?

whole code here:

$base=\DB::table('user')->select('firstname as name');
var_dump($base->get());//Everything is ok, I see the aliases 
var_dump($base->select('name')->get);//I see nothing, there's no column 'name'

more code here:

function getPerson(){
    return \DB::table('user')->select('firstname as name', 'age');
}

function getPet(){
    return \DB::table('pet')->select('petname as name', 'age');
}

function getNames($var){
    return $var->select('name')->where('age', 10)->get();
}

$base = getNames(getPerson());//empty here
$base = getNames(getPet());//empty here

The main problem is I got a lot of different queries and I want to put aliases on them and then prepare data for diagram with another query

Upvotes: 3

Views: 335

Answers (1)

Vladislav Rastrusny
Vladislav Rastrusny

Reputation: 29985

You cannot create permanent column aliases. But, you can create a view, which will contain fields named as you wish. And then point your model to this view as a regular table via $table property of the model.

Upvotes: 2

Related Questions