简体   繁体   中英

How to work with related tables in the Gridview : Yii2

I've written my code like this:

    <?= GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [
        //['class' => 'yii\grid\SerialColumn'],

        'quantity',
        [
            'header' => 'SN',
            'format' => 'raw',
            'value' => function($data) {
                $product = Product::findOne($data->product_ID);
                return $product->SN_required ? '<span class="glyphicon glyphicon-ok"></span>' : '';
            }
        ],

In order to show it like this:

在此处输入图片说明

Yet I think this is not correct (eventho it's working). Could someone please give me the correct notation for this sort of code?

I know this has to do with the model relations. That has been changed in Yii2.

 public function getProduct()
{
    return $this->hasOne(Product::className(), ['ID' => 'product_ID']);
}

You were on the right track. You can access relations inside the closure using $data->relation in your case:

'value' => function($data) {
    return $data->product->SN_required ? '<span class="glyphicon glyphicon-ok"></span>' : '';
}

You can view the Yii2 page on working with relations in data widgets for more information.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM