2016-03-01 98 views
0

我想知道我如何能夠計算出所有配方中成分的發生頻率。如何在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」

receipt_ingredients table

+0

我不認爲你需要創建一個型號爲支點,也如果我們folllow的laravel約定透視表應命名爲'ingredient_receipt' – user3813360

+0

哦,你」對了!我應該重命名它。謝謝! 也許有可能使用這個數據透視模型來計算這些東西 - 我必須嘗試一下。 – zer0

回答

0

不知道是否有更好的方式來做到這一點,但你可以只使用DB門面訪問您的數據透視表的表結構的屏幕截圖。

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

這是一個不錯的解決方案,謝謝。 我的樞軸模型也很好,可以完成同樣的事情:) – zer0

0

答案很好。

現在繼續下一步: 上面的方法計算由ingredient_id發生。

可是 - 我怎麼能做到以下幾點:

  • 取發生在配方中的所有成分
  • 計算每個成分
  • 排序成分DESC。
  • 返回他們作爲陣列/模型