Yii2 - Table alias with ActiveRecord

耗尽温柔 提交于 2019-12-22 05:40:32

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/49474661/yii2-table-alias-with-activerecord

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!