【问题标题】:How to count in pivot table in Laravel 5如何在 Laravel 5 中计算数据透视表
【发布时间】:2016-06-14 13:44:48
【问题描述】:

我想知道如何计算一种成分在所有食谱中出现的频率。

因为我使用的是withPivot,所以更难实现(我认为)。

模型成分:

class Ingredient extends Model
{
    public function receipt()
    {
        return $this->belongsToMany('Receipt','receipt_ingredients','ingredient_id','receipt_id')->withPivot('amount');
    }
}

型号收据

class Receipt extends Model
{
    public function ingredients()
    {
        return $this->belongsToMany('Ingredient','receipt_ingredients','receipt_id','ingredient_id')->withPivot('amount');
    }
}

Model ReceiptIngredient(我的数据透视表)

class ReceiptIngredient extends Model
{
    public $table = 'receipt_ingredients';

    public function receipt()
    {
        return $this->belongsTo('Receipt');
    }

    public function ingredient()
    {
        return $this->belongsTo('Ingredient');
    }
}

最后,我想列出每种成分以及食谱中出现的次数。

“receipt_ingredients”表结构的屏幕截图

receipt_ingredients table

【问题讨论】:

  • 我认为你不需要为数据透视表创建模型,如果我们遵循 laravel 约定,你的数据透视表也应该命名为ingredient_receipt
  • 哦,你是对的!我应该重命名它。谢谢!也许可以使用这个 Pivot-Model 来计算这些东西 - 我必须尝试一下。

标签: model-view-controller model laravel-5 blade


【解决方案1】:

不确定是否有更好的方法,但您可以使用 DB 外观来访问您的数据透视表。

$ingredientCount = DB::table('ingredient_receipt')
          ->groupBy('ingredient_id')
          ->where('ingredient_id', $ingredient_id)
          ->count();

【讨论】:

  • 这是一个不错的解决方案,谢谢。我的 Pivot-Model 也很好,可以完成同样的事情 :)
【解决方案2】:

答案很好。

现在进行下一步: 上面的方法是按成分id计算出现次数。

但是 - 我怎样才能做到以下几点:

  • 获取配方中出现的所有成分
  • 计算每种成分
  • 排序成分DESC。
  • 将它们作为数组/模型返回

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-10
    • 2016-03-09
    • 2015-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-28
    • 2016-02-06
    相关资源
    最近更新 更多