Answer the question
In order to leave comments, you need to log in
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();
}
Answer the question
In order to leave comments, you need to log in
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)
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';
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();
}
(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 questionAsk a Question
731 491 924 answers to any question