@snake2
Сразу пишу legacy код

Как отобразить значение из связанной таблицы в GridView Yii2, имея id нужного элемента?

Есть модель Product
/**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'types_id' => 'Тип',
            'img' => 'Img',
            'scu' => 'Scu',
            'name' => 'Name',
            'count' => 'Count',
        ];
    }

    /**
     * Gets query for [[Types]].
     *
     * @return \yii\db\ActiveQuery
     */
    public function getTypes()
    {
        return $this->hasOne(Type::class, ['types_id' => 'id']);
    }

и модель Type
public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'name' => 'Name',
        ];
    }

    /**
     * Gets query for [[Products]].
     *
     * @return \yii\db\ActiveQuery
     */
    public function getProducts()
    {
        return $this->hasMany(Product::class, ['types_id' => 'id']);
    }


Как отобразить name из модели Type, имея id типа?
<?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],

            ['attribute' => 'name', 'label' => 'Название'],
            ['attribute' => 'scu', 'label' => 'scu'],
            ['attribute' => 'types_id', 'label' => 'Тип', 'value' => 'types_id.name'],
            ['attribute' => 'img', 'label' => 'Изображение', 'format' => 'image'],
            ['attribute' => 'count', 'label' => 'Количество'],

            ['class' => 'yii\grid\ActionColumn'],
        ],
    ]); ?>
  • Вопрос задан
  • 89 просмотров
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы