Reputation: 780
I am wondering how to query a field in a pivot table in a Many-To-Many Relationship.
Lets assume we have this relation:
public function acciones(){
return $this->belongsToMany('App\Accion', 'inter_clientes_acciones', 'id_cliente', 'id_accion')->withPivot('valoracion', 'asistencia');
}
public function clientes(){
return $this->belongsToMany('App\Cliente', 'inter_clientes_acciones', 'id_accion', 'id_cliente')->withPivot('valoracion', 'asistencia');
}
What I have to get is the number of clients having boolean field asistencia
value true.
I have tried to do something like:
$clients = Cliente::findOrFail($id);
$number = $clients->acciones()->pivot->where('asistencia','=', true)->count();
But I had an error. Obviously.
Is there an eloquent way to get this count??
Upvotes: 1
Views: 128
Reputation: 1858
You can try this.
$number = Cliente::whereHas('acciones', function($q) {
$q->where('asistencia', '=', true);
})->count();
Upvotes: 1