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"`
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');
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With