Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2 - Table alias with ActiveRecord

Tags:

yii

yii2

I have a table with a long name, example products_with_a_long_name. The Model name is ProductsWithALongName. Now, I have a query where I need to select many columns from this table while joining with another table. Example:

ProductsWithALongName::find()
    ->select(['products_with_a_long_name.id', 'products_with_a_long_name.selling_price','client.name'])
    ->leftjoin('all_the_clients as client','products_with_a_long_name.clientId = client.id')
    ->where(['products_with_a_long_name.id' => $var]);

Now how can I use an alias for the first table, products_with_a_long_name as I'm using an alias for the second. I know I can use Query but in this case I need the result to be ActiveRecord so this is not an option in this case.

like image 328
mrateb Avatar asked Mar 25 '18 10:03

mrateb


1 Answers

You can use alias():

ProductsWithALongName::find()
    ->alias('p')
    ->select(['p.id', 'p.selling_price','client.name'])
    ->leftjoin('all_the_clients as client', 'p.clientId = client.id')
    ->where(['p.id' => $var]);
like image 71
ScaisEdge Avatar answered Dec 11 '22 14:12

ScaisEdge