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模型也很好,可以完成同样的任务:)
$ingredientCount = DB::table('ingredient_receipt')
->groupBy('ingredient_id')
->where('ingredient_id', $ingredient_id)
->count();