Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/codeigniter/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Model view controller 如何在Laravel 5的透视表中计数_Model View Controller_Model_Laravel 5_Blade - Fatal编程技术网

Model view controller 如何在Laravel 5的透视表中计数

Model view controller 如何在Laravel 5的透视表中计数,model-view-controller,model,laravel-5,blade,Model View Controller,Model,Laravel 5,Blade,我想知道我如何计算一种成分在所有食谱中出现的频率 因为我使用的是with pivot,所以实现起来比较困难(我想) 型号成分: class Ingredient extends Model { public function receipt() { return $this->belongsToMany('Receipt','receipt_ingredients','ingredient_id','receipt_id')->withPivot('a

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

因为我使用的是
with pivot
,所以实现起来比较困难(我想)

型号成分:

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');
    }
}
型号接收组件(我的数据透视表)

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

表格结构的屏幕截图,用于“收货配料”


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

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

下面是下一步: 上述方法按组分id统计发生次数

但是-我如何才能做到以下几点:

  • 取食谱中出现的所有配料
  • 数一数每种配料
  • 分类成分描述
  • 将它们作为数组/模型返回

我认为您不需要为pivot创建模型,如果我们遵循laravel约定,您的pivot表也应该命名为
配料收据
。哦,您说得对!我应该给它改名。非常感谢。也许可以使用这个枢轴模型来计算这些东西-我必须尝试一下。这是一个很好的解决方案,谢谢。我的Pivot模型也很好,可以完成同样的任务:)
$ingredientCount = DB::table('ingredient_receipt')
          ->groupBy('ingredient_id')
          ->where('ingredient_id', $ingredient_id)
          ->count();