mercredi 1 juin 2016

Eager Loading: Use `with` on pivot with eloquent relationship

There are 4 tables:

  • bundles: id, name
  • products: id, name
  • prices: id, name
  • bundle_product: id, bundle_id, product_id, price_id

There are 3 models:

  • Bundle
  • Product
  • Price

A Product has a Price when in a Bundle. I want to have all bundles with their associated products and associated prices. I can get all bundles with their product and the price id:

// I created a Bundle Model with a products method
class Bundle extends Model
{
    public function products()
    {
        return $this->belongsToMany()->withPivot('price_id');
    }
}

// Then I call this in a controller
$all_bundles = Bundle::with('products')->get();

// Then I can get the price Id of the first product of the first bundle
$price_id = Bundle::with('products')->first()
    ->products()->first()
    ->pivot->price_id;

But I dont want the price id, I want the price Model. Is there any way to preload the price from the pivot (with Eager Loading)?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire