【问题标题】:Search Model Via Table Yii2通过表 Yii2 搜索模型
【发布时间】:2020-01-29 16:21:38
【问题描述】:

我有三张桌子:

user
game
user_game

game.user_id - 创建游戏的用户。表 user_game 描述了 ADDED 游戏未创建的用户,它 有user_idgame_id 字段。我有 GameSearch 模型,它应该搜索当前用户添加的游戏。这里的搜索方法;

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;
}

所以我需要通过表 user_game 获取游戏列表,其中 user_id = 当前 ID 用户,game_id = 游戏 ID。请帮忙。

【问题讨论】:

  • 您的user 表中是否定义了特定关系?展示你的user 模型。

标签: database activerecord yii2 relationship


【解决方案1】:

首先你需要两个关系,首先在Game model 中,它将从user_game table (model) 获取一对多数据,然后在模型user_game 中你需要编写一个关系来从user @ 获取用户987654326@

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-26
    • 1970-01-01
    相关资源
    最近更新 更多