php 如何在Yii2表单中创建一个包含多个MySQL表数据的下拉列表?

omvjsjqw  于 2023-06-04  发布在  PHP
关注(0)|答案(1)|浏览(124)

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)) ?>

但说实话我真的不知道该怎么做。

but5z9lq

but5z9lq1#

在修复关系代码之前,关系不是hasMany是hasOne,因为这个Info_Table->Product_Table是一对一的。更改您的代码

public function getProductTable()
{
  return $this->hasOne(ProductTable::class, ['id' => 'product_id']);
}

所以,使用joinWith方法从数据库获取数据到下拉列表

$list = InfoTable::find()
  ->joinWith('productTable')
  ->asArray()
  ->all()

并在视图文件中使用

$form->field($InfoTable, 'product_id')
  ->dropDownList(ArrayHelper::map($list, function($item) {
    return $item['productTable']['name'] ?? '-';
  }, function($item) {
    return $item['productTable']['name'] ?? '-';
  })

相关问题