Yii2框架表加入

时间:2017-09-05 07:48:52

标签: php activerecord yii2 yii2-basic-app

我在模型中定义了以下关系

public function getApplication()
{
    return $this->hasOne(Applications::className(), ['application_id' => 'application_id']);
}

public function getAccount()
{
    return $this->hasOne(Accounts::className(), ['account_id' => 'account_id']);
}

public function getUser()
{
    return $this->hasOne(Users::className(), ['user_id' => 'oncall_id']);
}

在视图中:

GridView::widget([
'dataProvider' => $dataProvider,
'tableOptions' => ['class' => 'table  table-bordered table-hover table-striped'],
'columns' => [
    ['attribute' => 'oncalls.start_date', 'value' => 'start_date', 'headerOptions' => ['width' => '10%']],
    ['label' => 'Shift', 'value' => function($data) {
            if ($data->shift_start && $data->shift_end)
                return $data->shift_start . " -> " . $data->shift_end;
        }],
    'account.account_name',
    'application.application_name',
    'user.real_name',
    ['label' => 'Priority', 'value' => function ($dataProvider) {
            if ($dataProvider->priority == 1)
                return "Primary";
            else
                return "Secondary";
        }],
    'user.phone_1',
    'user.phone_2',
],

]);

但是,在调试器中,似乎存在过多的查询。 对于每个作业记录,都有适当的表格(用户,应用程序,帐户)的选择查询

如何避免查询这些查询并简单地使用包含所有这些值的连接语句?

1 个答案:

答案 0 :(得分:0)

您可以在查询中使用“with”或“joinWith”。

$dataProvider->query->with('account', 'application', 'user');

http://www.yiiframework.com/doc-2.0/yii-db-activequerytrait.html#with()-detail