M
M
Maxim Grechushnikov2015-04-27 21:58:11
Yii
Maxim Grechushnikov, 2015-04-27 21:58:11

Yii2, Relations, Something quarreled with logic. Push in the right direction?

Task: There are users. There are leaders, there are runners. The leader can have up to 5 runners that he trains. Relationship 1 to many. 1 leader, many runners.
The table is simple to disgrace: id, login, team_id, team_status
team_id - leader id in the same table
team_status - status, accepted, kicked out, etc...

public function getTeam(){
    if($this->getIsLeader())
      return $this->hasMany(self::className(), ['team_id'=>'id']);
    else
      return User::find()->where(['id'=>$this->team_id])->one()->getTeam(); // WTF?
  }

  public function getTeam_count(){
    return $this->getTeam()->count();
  }

Made it this way. If this is the leader, then I simply take out his team.
But what if I'm one of the team's runners? I can't figure out the logic in my head. How to display all members of the team I am a member of? Incl. and leader?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
R
restyler, 2015-05-13
@maxyc_webber

In your case, I would recommend that the leader set the team_id equal to his own id, then you will not need to make any complex conditions and union (unless, of course, I understood everything correctly from the task description)

M
Mishutka2000, 2015-04-28
@Mishutka2000

The coach has team_id = id
Then the query, no matter who the leader or runner is, will return the entire group:

SELECT id,  login FROM `user`
    WHERE team_id = (
            SELECT team_id FROM `user`
                 WHERE id = 1 # ID участника группы
       ) 
    AND team_status = 'active';

M
Maxim Grechushnikov, 2015-04-27
@maxyc_webber

until I came to this. but is there a normal option? I don't like this one for its complexity.

public function getTeam(){
    if($this->getIsLeader())
      return $this->hasMany(self::className(), ['team_id'=>'id']);
    else{
      return User::find()->where(['id'=>$this->team_id])->one()->getTeam()->where('id != :uid', [':uid'=>$this->id])
        ->union($this->hasOne(self::className(), ['id'=>'team_id']));
    }
  }

  public function getTeam_count(){
    return $this->getTeam()->count();
  }

although sql is ok
(SELECT * FROM `user` WHERE (id != 8538) AND (`team_id`=1)) UNION ( SELECT * FROM `user` WHERE `id`=1 )

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question