如何在数组助手映射 yii2 中按子数据分组
How to group by sub data in array helper map yii2
我有两张桌子
投资
id_investment
id_investment_type
name
投资类型
investment_type
id_investment_type
name
我使用函数
得到一个数组
ArrayHelper::map(Investment::find()->where(['id_investment_type'=>[1,2,3]])->all,'id_investment','name','id_investment_type');
这个return
1
investmentOneOfTypeOne
investmentTwoOfTypeOne
2
investmentOneOfTypeTwo
investmentTwoOfTypeTwo
我想用 investment_type
的名称更改 groupby
的 id_investment_type
例子
Build
Mounting Office
investmenTwo
...
Devices
invetmentOne
BuyLaptop
...
我试过如下
ArrayHelper::map(Investment::find()->where(['id_investment_type'=>[1,2,3]])->all,'id_investment','name','id_investment_type.name');
但不起作用。
请有人知道是否可以这样做。
谢谢!
您的投资中必须有model
这个方法:
/*
* return ActiveQuery
* id represent the investment type id column
* id_investment_type represent Investment table column which does have a value from
* Investment Type table
*/
public function getInvestmentType()
{
return $this->hasOne(InvestmentType::className(), ['id' => 'id_investment_type']);
}
然后你可以像这样构建你的地图:
ArrayHelper::map(Investment::find()
->with(['investmentType'])
->where(['id_investment_type'=>[1,2,3]])
->all(),'id_investment','investment_type.name');
这将 return 结果:
1 Mounting Office
2 InvestmenTwo
我有两张桌子
投资
id_investment
id_investment_type
name
投资类型
investment_type
id_investment_type
name
我使用函数
得到一个数组ArrayHelper::map(Investment::find()->where(['id_investment_type'=>[1,2,3]])->all,'id_investment','name','id_investment_type');
这个return
1
investmentOneOfTypeOne
investmentTwoOfTypeOne
2
investmentOneOfTypeTwo
investmentTwoOfTypeTwo
我想用 investment_type
的名称更改groupby
的 id_investment_type
例子
Build
Mounting Office
investmenTwo
...
Devices
invetmentOne
BuyLaptop
...
我试过如下
ArrayHelper::map(Investment::find()->where(['id_investment_type'=>[1,2,3]])->all,'id_investment','name','id_investment_type.name');
但不起作用。
请有人知道是否可以这样做。
谢谢!
您的投资中必须有model
这个方法:
/*
* return ActiveQuery
* id represent the investment type id column
* id_investment_type represent Investment table column which does have a value from
* Investment Type table
*/
public function getInvestmentType()
{
return $this->hasOne(InvestmentType::className(), ['id' => 'id_investment_type']);
}
然后你可以像这样构建你的地图:
ArrayHelper::map(Investment::find()
->with(['investmentType'])
->where(['id_investment_type'=>[1,2,3]])
->all(),'id_investment','investment_type.name');
这将 return 结果:
1 Mounting Office
2 InvestmenTwo