Yii2 - 带有 ActiveRecord 的表别名 [英] Yii2 - Table alias with ActiveRecord
问题描述
我有一个长名称的表,例如 products_with_a_long_name
.模型名称是 ProductsWithALongName
.现在,我有一个查询,我需要在与另一个表连接时从该表中选择许多列.示例:
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]);
现在我如何为第一个表使用别名,products_with_a_long_name
,因为我正在为第二个表使用别名.我知道我可以使用 Query
但在这种情况下我需要结果是 ActiveRecord
所以在这种情况下这不是一个选项.
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.
推荐答案
您可以使用 alias()
:
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]);
这篇关于Yii2 - 带有 ActiveRecord 的表别名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!