Yii2 框架表连接

Yii2 framework tables join

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

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',
],

]);

但是,在调试器中,似乎进行了过多的查询。 对于每条分配记录,都有一个 select 查询以查找适当的 table(用户、应用程序、帐户)

我怎样才能避免这些查询并简单地使用包含所有这些值的连接语句?

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

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

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