0
votes

I have two models: Game and Game_Assignment. Game_Assignment tells whose job it is to play a game.

I am trying to count the number of Game_Assignment's that a user has their id on that also have a specific value on the Game model that it relates to. I'll just get into the Models/the code

Game Model Relationship:

public function assignments() {
  return $this->hasMany('App\Models\Game_Assignment', 'game_id');
}

Game_Assignment Relationship:

public function game() {
  return $this->belongsTo('App\Models\Game', 'game_id');
}

Where things are going wrong (in a queue job, if that makes a difference)

$gamesDue = Game_Assignment::where('statistician_id', $statistician->id)->game->where('stats_done', '!=', 'yes')->count();

I have also tried the following two things, neither worked:

$gamesDue = Game_Assignment::where('statistician_id', $statistician->id)->game()->where('stats_done', '!=', 'yes')->count();

and...

$gamesDue = Game_Assignment::where('statistician_id', $defaultStatistician->id)->with(['games' => function($query) {
        $query->where('stats_done', '!=', 'yes');
      }])->count();

None of these work, and the first one I showed threw an error:

Property [game] does not exist on the Eloquent builder instance.

Anyone have an idea of where I am going wrong? I am using this link as my reference https://laravel.com/docs/5.8/eloquent-relationships#eager-loading

1

1 Answers

1
votes

When using the query builder of your Game_Assignment model, you cannot simply switch context to the query builder of Game. You can only call ->game() or ->game after you retrieved one or many model instances of Game_Assignment with first() or get().

So, in your particular case, you were looking for whereHas('game', $callback) (where $callback is a function that applies constraints on the foreign table) in order to add a constraint on the foreign table:

use Illuminate\Database\Eloquent\Builder;

$gamesDue = Game_Assignment::query()
    ->where('statistician_id', $statistician->id)
    ->whereHas('game', function (Builder $query) {
        $query->where('stats_done', '!=', 'yes');
    })
    ->count();

Side note: a column (stats_done) that seems to hold a boolean value (yes/no) should be of boolean type and not string/varchar.