Answer the question
In order to leave comments, you need to log in
How to make a row count cast through a crosstab?
There are 2 models User and Game. The game has 2 participants, in the future it is planned to do more, so I created a participants table with the fields "user_id, game_id".
In addition, the user may have referrals and I need to calculate the total number of games played by referrals.
Here is the code:
//User
public function games()
{
return $this->belongsToMany(Game::class, 'participants');
}
public function referrer()
{
return $this->hasOne(User::class, 'id', 'referred_by');
}
public function referrals()
{
return $this->hasMany(User::class, 'id', 'referred_by');
}
public function participants()
{
return $this->belongsToMany(User::class, 'participants');
}
public function ref_games_count()
{
$this->referrals()->whereHas('games')->selectRaw('participants.*, sum(participants.count)')->first();
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question