Eager Loading: 使用`with`和Eloquent关联一起在pivot上。

13 浏览
0 Comments

Eager Loading: 使用`with`和Eloquent关联一起在pivot上。

有4个表:

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

有3个模型:

  • Bundle
  • Product
  • Price

当一个Product在一个Bundle中时,它有一个Price。我想要所有带有它们关联的products和关联的pricesbundles。我可以获取带有产品和价格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)?

0