Y
Y
Yuri Kulaxyz2020-05-04 12:27:20
MySQL
Yuri Kulaxyz, 2020-05-04 12:27:20

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


And here is Game:
public function participants()
    {
        return $this->belongsToMany(User::class, 'participants');
    }

Tried something like
public function ref_games_count()
    {
        $this->referrals()->whereHas('games')->selectRaw('participants.*, sum(participants.count)')->first();
    }

But I realized that this is nonsense. Need help.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question