首页 > 解决方案 > 如何在数组助手映射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');

这个回报

1
  investmentOneOfTypeOne
  investmentTwoOfTypeOne
2
  investmentOneOfTypeTwo
  investmentTwoOfTypeTwo

我想通过 Investment_typeid_investment_typegroupby名称来更改

例子

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

但不起作用。

请有人知道是否可以这样做。

谢谢!。

标签: phpyii2

解决方案


您必须在您的投资中使用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');

这将返回以下结果:

1   Mounting Office
2   InvestmenTwo

推荐阅读