Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using whereHasMorph inside a local scope for MophByMany relationships

Tags:

laravel

I am needing to find out the current players on a given team. I have created a scope for this. The requirements are that it checks a pivot table to see if the left_at field is null or not. If it is Null that means they are still on the team (current player). The relationship is a polymorphic many to many relationship. The reason why it's polymorphic because a team can also have players come and go as well as coaches for the team.

Team.php

/**
 * Scope a query to only include current players.
 *
 * @param  \Illuminate\Database\Eloquent\Builder $query
 */
public function scopeCurrentPlayers($query)
{
    return $query->whereHasMorph('players', Player::class, function ($query) {
        $query->whereNull('left_at');
    });
}

**
 * Get all players that have been members of the stable.
 *
 * @return \Illuminate\Database\Eloquent\Relations\MorphByMany
 */
public function players()
{
    return $this->morphedByMany(Player::class, 'member')->using(Member::class)->withPivot(['joined_at', 'left_at']);
} 

Controller

$currentTeamPlayers = $team->currentPlayers()->get()->pluck('id');

I am expecting to get a collection of current players on the team however I am receiving the following error.

+exception: Symfony\Component\Debug\Exception\FatalThrowableError^ {#5387 -originalClassName: "TypeError" #message: "Argument 1 passed to Illuminate\Database\Eloquent\Builder::getBelongsToRelation() must be an instance of Illuminate\Database\Eloquent\Relations\MorphTo, instance of Illuminate\Database\Eloquent\Relations\MorphToMany given, called in /Users/jeffreydavidson/Projects/Ringside/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/QueriesRelationships.php on line 215"`

like image 898
Jeffrey Davidson Avatar asked Jul 27 '19 15:07

Jeffrey Davidson


1 Answers

whereHasMorph function only works for morphTo associations. Reference: https://laravel.com/docs/8.x/eloquent-relationships#querying-morph-to-relationships

For morphMany associations, you can simply use whereHas. Reference: https://laravel.com/docs/8.x/eloquent-relationships#querying-relationship-existence

So in your case,

public function scopeCurrentPlayers($query)
{
    return $query->whereHas('players', Player::class, function ($query) {
        $query->whereNull('left_at');
    });
}
like image 56
KULKING Avatar answered Nov 15 '22 19:11

KULKING