急切加载:在具有雄辩关系的枢轴上使用“with”
有4张桌子:
-
bundles
:id,名称 -
products
:id,名称 -
prices
:id,名称 -
bundle_product
:id, bundle_id, product_id, price_id
有3种型号:
Bundle
Product
Price
A 在 .我想拥有所有与他们的相关和关联的价格
。我可以获得所有捆绑包及其产品和价格ID:Product
Price
Bundle
bundles
products
// I created a Bundle Model with a products method
class Bundle extends Model
{
public function products()
{
return $this->belongsToMany(Product::class)->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;
但是我不想要价格ID,我想要价格模型。有没有办法从枢轴预加载价格(使用急切加载)?