S
S
snake22021-08-02 20:57:51
Yii
snake2, 2021-08-02 20:57:51

How to display value from linked table in GridView Yii2 having id of desired element?

There is a Product model

/**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'types_id' => 'Тип',
            'img' => 'Img',
            'scu' => 'Scu',
            'name' => 'Name',
            'count' => 'Count',
        ];
    }

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

and model Type
public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'name' => 'Name',
        ];
    }

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


How to display the name from the Type model, given the 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'],
        ],
    ]); ?>

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question