【问题标题】:Laravel - Sum of pivot table results given a criteriaLaravel - 给定标准的数据透视表结果的总和
【发布时间】:2014-12-23 02:37:59
【问题描述】:

场景 一个警报可以有很多条件,很多条件可以有我的警报。

一个用户被分配到一个标准。当用户查看他们所有的criteria 时,我希望它显示有多少匹配警报的总和(存储在数据透视表中)。该关系使用结构如下的数据透视表:

例如,我可以访问警报和条件数据,它还应该告诉我对于criteria_id = 73,有一个警报匹配id_2

所以Eloquent 公式目前是:

public function getIndex()
    {
        $alerts = Criteria::with('coordinate', 'alerts')
        ->where('user_id', '=', Auth::user()->id)
        ->get();

        $this->layout->content = View::make('users.alert.index', 
            array('alerts' => $alerts));
    }

警报模型中的关系

public function criterias()
    {
        return $this->belongsToMany('Criteria')->withTimestamps();
    }

标准模型中的关系

public function alerts()
{
    return $this->belongsToMany('Alert')->withTimestamps();
}

如果您需要任何进一步的信息,请告诉我。非常感谢您的帮助。

【问题讨论】:

  • 您要计算所有警报还是只计算符合该条件的唯一警报?
  • 可能有多个条件与该用户相关联。因此,如果有意义,就需要“计算与属于该用户的每个条件相关的所有警报”?

标签: laravel laravel-4 eloquent pivot-table


【解决方案1】:

我使用上面@JarekTkaczyk 的示例解决了我的问题。

Getting count from pivot table in laravel eloquent

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-10
    • 2021-08-17
    • 1970-01-01
    相关资源
    最近更新 更多