如何在 Laravel 5 中计算枢轴 table

How to count in pivot table in Laravel 5

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

因为我正在使用 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');
    }
}

模型收据成分(我的支点table)

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

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

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

最后,我想要一份每种成分的清单以及食谱中出现的次数。

"receipt_ingredients"

的 table 结构的屏幕截图

receipt_ingredients table

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

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

回答的很好

现在进行下一步: 上面的方法通过 ingredient_id.

计算出现次数

但是 - 我怎样才能完成以下任务:

  • 获取食谱中出现的所有成分
  • 计算每种成分
  • 排序 成分描述
  • Return 他们是 array/model