9 months ago

Using related Model true/false functions in eloquent queries

Posted 9 months ago by hunterhawley


I've got three models: Game, User, and Game_Assignment

The users are assigned games to watch through the Game_Assignment Model. Games can have multiple Game_Assignment's, and Users can too.

For each game, the most recent Game_Assignment is the one that should be used, the others are just for reference sake. This is because a game might be assigned to a user and it might need to be re-assigned for whatever reason. Users have multiple Game_Assignments because they may have multiple games to watch.

Now, I am trying to get a count of Game's assigned for each User, but only if the assignment is the most recent one for that game.

On User, I have the following function:

public function current_game_assignments() {
  return $this->hasMany('App\Models\Game_Assignment', 'statistician_id')->where('isLatestAssignment', true);

"isLatestAssignment" comes from Game_Assignment, and here is that function:

public function isLatestAssignment() {
  if($this->game->latestAssignment()->id == $this->id) {
    return true;
  } else {
    return false;

Finally, "latestAssignment" comes from Game, and here is that one too:

public function latestAssignment() {
  return $this->hasOne('App\Models\Game_Assignment', 'game_id')->latest();

I know User is causing the problem, because Eloquent thinks "isLatestAssignment" is a column, not a function.

Here is the error I am getting:

Column not found: 1054 Unknown column 'isLatestAssignment'

Any ideas on how I can achieve this?

Please sign in or create an account to participate in this conversation.