【发布时间】:2018-08-09 09:25:39
【问题描述】:
我在 yii 上有点挣扎。 我目前正在尝试显示具有多对多关系的数据。
我有:
table set
name
description
table item
name
description
table subinventory
name
description
and table setDetail who link them all
set_id
item_id
subinventory_id
我为 Set 生成了一个 crud 并添加了一个 Gridview 来显示集合中存在的所有项目(保存在 setDetail 表中) 数据提供者就是这个
$dataProvider= new ActiveDataProvider(
[ 'query' => $this->hasMany(SetDetail::className(), ['set_id' => 'id'])
]
它运行良好,但它当然会显示项目和子库存的 ID。 我可以在 gridview 中检索数据,但它会为每个我认为不理想的数据发出请求。
我想做一个这样的 viaTable:
$dataProvider= new ActiveDataProvider(
[ 'query' => $this->hasMany(SetDetail::className(), ['set_id' => 'id'])->viaTable('item',['id => 'item_id'])
]
但这显然不起作用,因为 item_id 不在 set 表中,而是在 setDetail 表中。
所以我的问题:有没有办法正确(我的意思是使用 yii 框架)使用 viaTable 和查询提供的数据? 我肯定不是很清楚,所以请不要犹豫,纠正我
这里是setDetail模型中生成的关系。
/**
* @return \yii\db\ActiveQuery
*/
public function getItem()
{
return $this->hasOne(Item::className(), ['id' => 'item_id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getReason()
{
return $this->hasOne(Reason::className(), ['id' => 'reason_id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getReference()
{
return $this->hasOne(Reference::className(), ['id' => 'reference_id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getSet()
{
return $this->hasOne(Set::className(), ['id' => 'set_id']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getSubinventory()
{
return $this->hasOne(Subinventory::className(), ['id' => 'subinventory_id']);
}
【问题讨论】:
-
您是否使用
SetModel 创建dataProvider?然后添加SetDetail模型,其中包含所有关系。 -
@InsaneSkull 是的,我在 Set 模型中创建了数据提供者。我很确定我在搞砸它,并且有一种更好的方法可以做到这一点。另外,我可能没有正确完成我想要实现的数据库
-
该死的,我只是测试了一些没有信念的东西及其工作......
标签: activerecord yii2 many-to-many