如何在Laravel 5中的数据透视表中计数
问题描述:
我想知道我如何能够计算出所有配方中成分的发生频率。如何在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');
}
}
型号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”
答
不知道是否有更好的方式来做到这一点,但你可以只使用DB门面访问您的数据透视表的表结构的屏幕截图。
$ingredientCount = DB::table('ingredient_receipt')
->groupBy('ingredient_id')
->where('ingredient_id', $ingredient_id)
->count();
+0
这是一个不错的解决方案,谢谢。 我的枢轴模型也很好,可以完成同样的事情:) – zer0
答
答案很好。
现在继续下一步: 上面的方法计算由ingredient_id发生。
可是 - 我怎么能做到以下几点:
- 取发生在配方中的所有成分
- 计算每个成分
- 排序成分DESC。
- 返回他们作为阵列/模型
我不认为你需要创建一个型号为支点,也如果我们folllow的laravel约定透视表应命名为'ingredient_receipt' – user3813360
哦,你”对了!我应该重命名它。谢谢! 也许有可能使用这个数据透视模型来计算这些东西 - 我必须尝试一下。 – zer0