M
M
Maxim Grechushnikov2015-04-03 14:19:19
Yii
Maxim Grechushnikov, 2015-04-03 14:19:19

Yii2: Complex relation and dataprovider. Can you help?

So. There is a social network. A bunch of tables and dependencies. Here is a part of them.
A user can be a club owner (club.owner_id) and can be a member of clubAX (users_clubs) - many_many
Zt-sB8nK_HQ.jpg
Each user generates events. Events are bound only to the user. It is necessary to draw a list of events in the club in the gridview. That is, display the events of all users related to a particular club.
Sketched this sql

SELECT
          e.id, e. c.club_id, u.name
        FROM
          events AS e

          JOIN user AS u
            ON e.owner_id = u.id
          JOIN users_clubs AS uc
            ON uc.user_id = u.id
          JOIN clubs AS c
            ON c.id = uc.club_id

        WHERE
          c.id = :club_id

Models available:
User
public function getClubs(){
    return $this->hasMany(Club::className(), ['id'=>'club_id'])
      ->viaTable('users_clubs', ['user_id'=>'id']);
  }

event
public function getOwner(){
    return $this->hasOne(User::className(), ['id'=>'owner_id']);
  }

Club
public function getMembers($count = 100){
    return $this->hasMany(User::className(), ['id'=>'user_id'])
      ->limit($count)
      ->viaTable('users_clubs', ['club_id'=>'id'], function($query){
        $query->where(['status'=>User::STATUS_CLUB_JOINED_APPROVED]);
      });
  }

Search event models
public function search($params) {

    $query = Event::find(); // я так понимаю вся движуха должна быть здесь или вынесена в EventQuery впоследствии
    $this->scenario = 'search';

    $dataProvider = new \yii\data\ActiveDataProvider([
      'query'=>$query,
    ]);
    
    if (!($this->load($params) && $this->validate())) {
      return $dataProvider;
    }

    $query->andFilterWhere(['id' => $this->id]);


    return $dataProvider;
  }

Does anyone have the time and opportunity to help with the question?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Grechushnikov, 2015-04-03
@maxyc_webber

... $params['club_id'] = 1 ...
$query = Event::find()->joinWith(['owner.clubs'=>function($query) use ($params) {
  return $query->where(['clubs.id'=>$params['club_id']]);
}]);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question