【问题标题】:Laravel 5.1 - Querying a field of a pivot table with where EloquentLaravel 5.1 - 使用 Eloquent 查询数据透视表的字段
【发布时间】:2016-02-04 20:07:30
【问题描述】:

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

假设我们有这个关系:

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();

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

有没有一种雄辩的方法来获得这个计数??

【问题讨论】:

    标签: php mysql eloquent laravel-5.1


    【解决方案1】:

    你可以试试这个。

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

    【讨论】:

      猜你喜欢
      • 2015-09-30
      • 2018-11-11
      • 2015-06-24
      • 2015-12-28
      • 1970-01-01
      • 2018-12-08
      • 1970-01-01
      • 2016-02-12
      相关资源
      最近更新 更多