Programador Adagal
Programador Adagal

Reputation: 780

Laravel 5.1 - Querying a field of a pivot table with where Eloquent

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

Answers (1)

NULL
NULL

Reputation: 1858

You can try this.

$number = Cliente::whereHas('acciones', function($q) {
               $q->where('asistencia', '=', true);
          })->count();

Upvotes: 1

Related Questions