OKyJIucT
9/17/2016 - 7:21 AM

Поиск по связанным таблицам

Поиск по связанным таблицам

GridView (views/logs/index.php)

<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,
    'columns' => [
        ['class' => 'yii\grid\SerialColumn'],

        'userMail',
        'userAction',
        [
            'label' => 'action',
            'value' => 'action.text',
        ],
        'ip',

        ['class' => 'yii\grid\ActionColumn'],
    ],
]); ?>

Logs.php

/* Геттер для почты юзера */
public function getUserMail()
{
    return $this->user->email;
}

/* Геттер для экшена юзера */
public function getUserAction()
{
    return $this->action->text;
}

LogsSearch.php

public $userMail;
public $userAction;
    
public function rules()
{
    return [
        [['id', 'user_id', 'action_id', 'created_at', 'updated_at'], 'integer'],
        [['text', 'ip', 'userMail', 'userAction'], 'safe'],
    ];
}

...

$dataProvider->setSort([
    'attributes' => [
        'userMail' => [
            'asc' => ['users.userMail' => SORT_ASC],
            'desc' => ['users.userMail' => SORT_DESC],
            'label' => 'Пользователь'
        ],
        'userAction' => [
            'asc' => ['actions.text' => SORT_ASC],
            'desc' => ['users.text' => SORT_DESC],
            'label' => 'Действие'
        ],
    ]
]);

$this->load($params);

...

$query->joinWith(['user' => function ($q) {
    $q->where('users.email LIKE "%' . $this->userMail . '%"');
}]);

$query->joinWith(['action' => function ($q) {
    $q->where('actions.text LIKE "%' . $this->userAction . '%"');
}]);

return $dataProvider;