【问题标题】:yii2 connect tables in gridviewyii2在gridview中连接表
【发布时间】:2017-06-17 10:05:38
【问题描述】:

我有主表和几个子表。

主表ProductproductID / productNameID / productColorID

和子表

产品名称产品名称ID/名称

productColorproductColorID / 名称

在主表中,我只插入子表的 ID。 为了获得普通名称而不是 ID,我在产品模型中使用了函数:

public function getProductName()
{
    return $this->hasOne(ProductName::className(), ['nameID' => 'productNameID']);
}

public function getProductColor()
{
    return $this->hasOne(ProductColor::className(), ['colorID' => 'productColorID']);
}

如果我只在视图中使用模型,我可以写 $model->productName['name'] 从子表中获取名称。

但我想创建 GridView。为此,我从 Gii 创建了默认 CRUD。如您所知,GridView 使用 SearchModel。 当我在列表中执行此操作时,我只从主表中获得了 ID。可能是因为 SearchModel 中没有自定义函数 我的意思是现在与存储名称的子表没有任何联系。 那么如何将我的主表连接到 GridView 中的子表?应该怎么做才能做到这一点?

【问题讨论】:

    标签: gridview yii2 yii2-model yii2-grid


    【解决方案1】:

    有几种方法可以做到: 第一个是最简单的(我建议),你可以写下你的关系名称,然后访问你需要在一个字符串中显示的属性:

    <?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => [
            'id',
    
            'productName.name', // Here it is
    
            ['class' => 'yii\grid\ActionColumn'],
        ],
    ]); ?>
    

    另一种方式(并且更动态)您可以调用匿名函数来显示所需的值,如下所示:

    <?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => [
            'id',
    
            [
                'attribute' => 'category_id',
                'value' => function (Product $product) {
                    return $product->category->name;
                    // make sure your model has productName, or it will throw Non-object exception
                    // return $product->category ? $product->category->name : null; 
                },
            ],
    
            ['class' => 'yii\grid\ActionColumn'],
        ],
    ]); ?>
    

    关于在这些相关属性上应用搜索,您可以在 Yiiframwork 文档Yii 2.0: Displaying, Sorting and Filtering Model Relations on a GridView中了解更多信息

    此外,请确保您预先加载相关表,这样您的 gridview 就不会使用 $model-&gt;with()$model-&gt;joinWith() 函数调用大量单独的查询

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多