Yii2 - 活动记录中的trasitive依赖

时间:2016-10-24 10:24:31

标签: php mysql activerecord yii2

我有3张桌子。

Product [ProductId, ProductName], VendorProduct[VPid, ProductId, VPprice], Deals[DealId, VPid, DealPrice]

我想在GridView中使用活动记录显示交易。我定义了关系但无法从表Product中访问ProductName。

Deals.*, VendorProduct.VPid, Product.ProductName

这是我想要的结果。 我的DealsSearch模型就像。

$query = Deals::find()->joinWith(['vendorProduct', 'vendorProduct.product']);

我将$query传递给ActiveDataProvider

$dataProvider = new ActiveDataProvider([
   'query' => $query,
]);

我的GridView代码:

GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [
        ['class' => 'yii\grid\SerialColumn'],
        'DealId',
        'VPid',
        'DealPrice',
        [
          'label' => 'Product Name',
          'attribute' => 'vendorProducts.product.ProductName',
        ],
    ],
]);

使用普通连接查询很简单,但我需要使用ActiveRecord类来执行此操作。

编辑:

简而言之,我想要使用ActiveRecord进行以下查询的结果。

SELECT Deals.*, VendorProduct.VPid, Product.ProductName
FROM Deals
JOIN VendorProduct ON VendorProduct.VPid = Deals.VPid
JOIN Product ON Product.ProductId = VendorProduct.ProductId;

当我在视图中打印$model->vendorProduct时,我得到了以下数组。 (为了便于阅读,我删除了额外的列。)

backend\models\VendorProducts Object
(
    [_attributes:yii\db\BaseActiveRecord:private] => Array
        (
            [VPid] => 3
            [ProductId] => 4175
            [VPprice] => 0
        )
    [_related:yii\db\BaseActiveRecord:private] => Array
        (
            [product] => backend\models\Product Object
                (
                    [_attributes:yii\db\BaseActiveRecord:private] => Array
                        (
                            [ProductId] => 4175
                            [ProductName] => Human Resource Consultancy
                        )

                )

        )

    [_errors:yii\base\Model:private] => 
    [_validators:yii\base\Model:private] => 
    [_scenario:yii\base\Model:private] => default
    [_events:yii\base\Component:private] => Array
        (
        )

    [_behaviors:yii\base\Component:private] => Array
        (
        )

)

2 个答案:

答案 0 :(得分:4)

<强> GridView的

<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [
        ['class' => 'yii\grid\SerialColumn'],
        'vendorProduct.VPprice',
        [
          'label' => 'Product Name',
          'attribute' => 'vendorProduct.product.ProductName',
        ],
    ],
]); ?>

答案 1 :(得分:0)

您是否尝试使用自定义值,如下所示..

GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [
        ['class' => 'yii\grid\SerialColumn'],
        'DealId',
        'VPid',
        'DealPrice',
        [
          'label' => 'Product Name',
          'attribute' => 'vendorProducts.product.ProductName', // here use attribute ProductName, 
          'value'=> 'vendorProducts.product.ProductName',
        ],
    ],
]);