Yii 2试图显示一个下拉列表,其中包含来自2个数据库表的信息
嗨,我正在尝试在Yii 2中的表单中创建一个下拉列表,它使用某个数据库表的ID,并从另一个表中获取属于该ID的名称。以下是我尝试过的:
为两个表创建一个模型,创建一个$form->field()并链接两个表。我试图从一个表中获取id,并从另一个表中获取名称(id是链接的)。
所以这个表看起来像这样:
// table 1 Info_Table table 2 Product_Table
id | product_id | product_type id | product_name
-----------------------------------------------------------
1 500 Toy 500| hot wheels
2 501 Toy 501| Lego
我为这两个表都建立了一个模型,并在InfoTable模型中将它们链接起来:(我有每个表的基本模型)
/**
* @return ActiveQuery
*/
public function getProductTable()
{
return $this->hasMany(ProductTable::class, ['id' => 'product_id']);
}
下面是我尝试在下拉列表中显示名称的方式:
<?= $form->field($InfoTable, 'product_id')->dropDownList(ArrayHelper::map(InfoTable::find()->all(), InfoTable->ProductTable->name, InfoTable->ProductTable->name)) ?>
但说实话我真的不知道该怎么做。
1条答案
按热度按时间but5z9lq1#
在修复关系代码之前,关系不是hasMany是hasOne,因为这个
Info_Table->Product_Table
是一对一的。更改您的代码所以,使用
joinWith
方法从数据库获取数据到下拉列表并在视图文件中使用