在 Yii 框架中使用 via 与多对多关系



我在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 并添加了一个网格视图来显示集合中存在的所有项目(保存在 setDetail 表中( 数据提供者是这个

$dataProvider= new ActiveDataProvider(
[ 'query' => $this->hasMany(SetDetail::className(), ['set_id' => 'id'])
]

它工作得很好,但当然它显示了项目和子库存的ID。 我可以在网格视图中检索数据,但它会为每个数据发出请求,我认为这并不理想。

我想做一个这样的 viaTable:

$dataProvider= new ActiveDataProvider(
[ 'query' => $this->hasMany(SetDetail::className(), ['set_id' => 'id'])->viaTable('item',['id => 'item_id'])
]

但它显然不起作用,因为item_id不在设置表中,而是在 setDetail 表中。

所以我的问题:有没有办法正确(我的意思是使用 yii 框架(使用 viaTable 和查询提供的数据? 我肯定不是很清楚,所以不要犹豫,纠正我

这里生成的关系在 setDetail 模型中。

/**
* @return yiidbActiveQuery
*/
public function getItem()
{
return $this->hasOne(Item::className(), ['id' => 'item_id']);
}
/**
* @return yiidbActiveQuery
*/
public function getReason()
{
return $this->hasOne(Reason::className(), ['id' => 'reason_id']);
}
/**
* @return yiidbActiveQuery
*/
public function getReference()
{
return $this->hasOne(Reference::className(), ['id' => 'reference_id']);
}
/**
* @return yiidbActiveQuery
*/
public function getSet()
{
return $this->hasOne(Set::className(), ['id' => 'set_id']);
}
/**
* @return yiidbActiveQuery
*/
public function getSubinventory()
{
return $this->hasOne(Subinventory::className(), ['id' => 'subinventory_id']);
}

我回答我自己的问题,主要是因为我在真正搜索之前问...

我想使用via,但左联是我需要的。另外,我测试了简单的database.column及其工作。所以我的代码就是这样。

$dataProvider= new ActiveDataProvider(
[ 'query' => $this->hasMany(SetDetail::className(), ['set_id' => 'id'])
->leftJoin('item','`item`.`id` = `setDetail`.`item_id`')
->leftJoin('subinventory','`subinventory`.`id` = `setDetail`.`subinventory_id`')
->select([
"`setDetail`.*",
"`item`.name AS item_name",
"`subinventory`.name AS subinventory_name",
])
]
);

并且我还需要在 SetDetail 模型中添加subinventory_name和item_name:

class SetDetail extends yiidbActiveRecord
{
public $item_name;
public $subinventory_name;
…

你可以尝试这样的事情:

$dataProvider= new ActiveDataProvider([
'query' => Set::find()->with(['setDetails.item', 'setDetails.subinventory'])->where(['id' => $id]);
]);

在这里,setDetails是您在模型中拥有的许多关系名称Set

供查看

$model = Set::find()
->with(['setDetails.item', 'setDetails.subinventory'])
->where(['id' => $id])
->one();

setDetails上使用 foreach 以显示每个 SetDetail 模型。

最新更新