php - 如何在数组助手映射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_type
的groupby
名称来更改
例子
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');
这将返回以下结果:
1 Mounting Office
2 InvestmenTwo
推荐阅读
- javascript - 是否有一种编程方式来检测 Cloud Function 运行在哪个区域?
- php - PHP - 无法重命名文件 - “文件名、目录名或卷标语法不正确”
- angular - 如何在角度 6 中选中默认复选框?
- azure - 指标不适用于 Azure 中继
- sql-server - IX pagelock 导致的 SQL Server 死锁
- json - 使用资源管理器模板的数据工厂自定义参数
- json - 当映射 int 值时,从 JSON 映射模型给我一个错误
- selenium-webdriver - 即使使用选择类和操作类,下拉选择也无法从列表中选择元素
- android - 如何在 android Nougat 及以上版本中创建 Notification.contentView?
- shell - 在目标 shell 脚本中,如何知道它是从哪个符号链接链接的文件?