How to show yii2 database relation in view

2019-09-12 06:29发布

I am new in yii2. I don't know much about table relation. I have a 3 tables shops promotions and promotion_details. promotion_details contains promotion id and shop id. promotion has status like active or inactive. i want display in shop view only active promotions. How can i Do that? Thanks in advance

1条回答
Anthone
2楼-- · 2019-09-12 06:55

In you promotion_detail view add a getter function for relation and a getter function for the field

/* ActiveRelation */
public function getPropomition()
{
   return $this->hasOne(Promotion::className(), ['id' => 'promotion_id']);
}

/* Getter for status name */
public function getStatus() {
   return $this->prpmotion->status;
}

in view

echo GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [
        ['class' => 'yii\grid\SerialColumn'],
        'id',
        .......
        'status',
        ['class' => 'yii\grid\ActionColumn'],
    ]
]);

this guide could be useful http://www.yiiframework.com/wiki/621/filter-sort-by-calculated-related-fields-in-gridview-yii-2-0/

查看更多
登录 后发表回答