0
votes

I have three tables:

user
game
user_game

game.user_id - user which CREATE game. Table user_game describes users that ADDED games not create, it has user_id and game_id fields. I have GameSearch Model which should search current user ADDED games. Here The search method;

public function search($params)
{
    // HERE I SHOULD GET ONLY GAMES WHICH ADDED BY USER via table user_game 
    $query = Game::find();

    $dataProvider = new ActiveDataProvider([
        'query' => $query,
        'sort' => [
            'defaultOrder' => [
                'sorting' => SORT_DESC,
            ]
        ],
    ]);

    if (!empty($params['pageSize'])) {
        $dataProvider->pagination->pageSize = $params['pageSize'];
    }

    $this->load($params);

    if (!$this->validate()) {
        // uncomment the following line if you do not want to return any records when validation fails
        // $query->where('0=1');
        return $dataProvider;
    }

    // grid filtering conditions
    $query->andFilterWhere([
        'id' => $this->id,
        'user_id' => $this->user_id,
        'visible' => $this->visible,
        'sorting' => $this->sorting,
        'created_at' => $this->created_at,
        'updated_at' => $this->updated_at,
    ]);

    $query->andFilterWhere(['like', 'name', $this->name])
        ->andFilterWhere(['like', 'slug', $this->slug])
        ->andFilterWhere(['like', 'image', $this->image])
        ->andFilterWhere(['like', 'description', $this->description])
        ->andFilterWhere(['>=', 'created_at', $this->date_from ? $this->date_from : null])
        ->andFilterWhere(['<=', 'created_at', $this->date_to ? $this->date_to : null])
        ->andFilterWhere(['>=', 'updated_at', $this->date_upd_from ? $this->date_upd_from : null])
        ->andFilterWhere(['<=', 'updated_at', $this->date_upd_to ? $this->date_upd_to : null]);

    return $dataProvider;
}

So i need get games list via table user_game where user_id = current Id user, game_id = game id. Please help.

1
Do you have specific relation defined in your user table? show your user model. - Serghei Leonenco

1 Answers

1
votes

first of all you need two relation in first in Game model which will fetch one to many data from user_game table (model), then in model user_game you need write a relation to get user from user table (model)

$query->joinWith(['userGame', 'userGame.user']);

->andFilterWhere(['=', 'tbl_user.id', Yii::app()->user->id])