【问题标题】:How to work with related tables in the Gridview : Yii2如何在 Gridview 中使用相关表:Yii2
【发布时间】:2015-05-02 21:13:47
【问题描述】:

我的代码是这样写的:

    <?= 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>' : '';
            }
        ],

为了这样显示它:

但我认为这是不正确的(即使它正在工作)。有人可以给我这种代码的正确符号吗?

我知道这与模型关系有关。在 Yii2 中已经改变了。

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

【问题讨论】:

    标签: php gridview model yii2 relation


    【解决方案1】:

    你在正确的轨道上。在您的情况下,您可以使用 $data-&gt;relation 访问闭包内的关系:

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

    您可以查看Yii2 page on working with relations in data widgets了解更多信息。

    【讨论】:

    • 除非您想查看“ 'raw', ' 效果很好,谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多