mardi 1 mars 2016

How to count in pivot table in Laravel 5

I would like to know how I can count how often an ingredient occurs in all recipes.

Because I'm using withPivot it's harder to achieve (I think).

Model Ingredient:

class Ingredient extends Model
{
    public function receipt()
    {
        return $this->belongsToMany('Receipt','receipt_ingredients','ingredient_id','receipt_id')->withPivot('amount');
    }
}

Model Receipt

class Receipt extends Model
{
    public function ingredients()
    {
        return $this->belongsToMany('Ingredient','receipt_ingredients','receipt_id','ingredient_id')->withPivot('amount');
    }
}

Model ReceiptIngredient (my pivot table)

class ReceiptIngredient extends Model
{
    public $table = 'receipt_ingredients';

    public function receipt()
    {
        return $this->belongsTo('Receipt');
    }

    public function ingredient()
    {
        return $this->belongsTo('Ingredient');
    }
}

In the end, I would like to have a list of each ingredient with the number of occurences in recipes. receipt_ingredients table



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire