Eager Loading: 使用`with`和Eloquent关联一起在pivot上。
- 论坛
- Eager Loading: 使用`with`和Eloquent关联一起在pivot上。
13 浏览
Eager Loading: 使用`with`和Eloquent关联一起在pivot上。
有4个表:
bundles
:id,nameproducts
:id,nameprices
:id,namebundle_product
:id,bundle_id,product_id,price_id
有3个模型:
Bundle
Product
Price
当一个Product
在一个Bundle
中时,它有一个Price
。我想要所有带有它们关联的products
和关联的prices
的bundles
。我可以获取带有产品和价格ID的所有bundles:
//我在Bundle模型中创建了一个products方法 class Bundle extends Model { public function products() { return $this->belongsToMany(Product::class)->withPivot('price_id'); } } //然后在控制器中调用这个方法 $all_bundles = Bundle::with('products')->get(); //然后我可以获取第一个bundle的第一个产品的价格ID $price_id = Bundle::with('products')->first() ->products()->first() ->pivot->price_id;
但是我不想要价格ID,我想要价格模型。有没有办法预加载pivot中的价格(使用Eager Loading)?