I've got a many-to-many relationship between a user and a match, and I have a availability column on the pivot table which is an enum:
'available', 'not-available', 'tbc'
<?p
...
class User extends Model
public function matches() {
return $this->belongsToMany(Match::class)->withPivot('availability');
}
<?p
...
class Match extends Model
public function users() {
return $this->belongsToMany(User::class)->withPivot('availability');
}
| match_id | user_id | availability |
|---|---|---|
| 4 | 2 | available |
| 4 | 1 | tbc |
| 4 | 3 | available |
| 4 | 5 | tbc |
| 4 | 4 | not-available |
| ... | ... | ... |
| 4 | 4 | not-available |
I'm trying to get the count of the availabilities for the players for a given match.
So that I can return something like:
[
"availability" => "available",
"count" => 17,
],
[
"availability" => "not-available",
"count" => 12,
],
[
"availability" => "tbc",
"count" => 4,
]
I feel like I should be able to use a withCount when I eager load the users on a model, but I can't workout how to do it on the pivot data.