mrateb
mrateb

Reputation: 2499

Yii2 - Table alias with ActiveRecord

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.

Upvotes: 12

Views: 11820

Answers (1)

ScaisEdge
ScaisEdge

Reputation: 133360

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]);

Upvotes: 30

Related Questions