【发布时间】: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”表结构的屏幕截图
【问题讨论】:
-
我认为你不需要为数据透视表创建模型,如果我们遵循 laravel 约定,你的数据透视表也应该命名为
ingredient_receipt -
哦,你是对的!我应该重命名它。谢谢!也许可以使用这个 Pivot-Model 来计算这些东西 - 我必须尝试一下。
标签: model-view-controller model laravel-5 blade