Laravel 5.1 - 查询数据透视表的字段,其中有口才


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

我想知道如何在多对多关系中查询数据透视表中的字段。

让我们假设我们有这样的关系:

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');
}

我必须得到的是布尔字段asistencia值为 true 的客户端数量。

我尝试做这样的事情:

$clients = Cliente::findOrFail($id);
$number = $clients->acciones()->pivot->where('asistencia','=', true)->count();

但是我有一个错误。明显地。

有没有雄辩的方法可以得到这个计数??

你可以

试试这个。

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