共有4个表格:

  • bundles: id, name
  • products:身份证,姓名
  • prices:身份证,姓名
  • 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(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;

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)?

推荐答案

One solution could be adding a BundleProduct model for the pivot. Then link the BundleProduct object to Bundle model:

class Bundle extends Model
{
    public function bundleProducts()
    {
        return $this->hasMany(BundleProduct::class, 'bundle_id', 'id');
    }
}

To get all your bundles with their associated products and prices in this bundle, just do:

Bundle::with('bundleProducts.product', 'bundleProducts.price')->get();

这对我很管用,希望能帮助其他人.

Laravel相关问答推荐

如何在 Laravel 中使用 Vue 路由?

如何使用动态翻译键翻译 Laravel硬编码字符串(还有 1 个错误)..(验证异常类)

Laravel 9 如何将 url 中的参数从一个控制器传递到另一个控制器?

在 Laravel 中清除 Routes&config:cache 后未定义的常量

验证错误后的 Laravel 自定义重定向

Laravel:如何强制使用 HTTPS?

判断 Laravel 中是否存在唯一索引键

Laravel Blade 模板 @foreach 订单

Laravel 将 JSON 转换为数组?

Laravel 扩展验证自定义消息

删除表后如何重新迁移laravel迁移

向 Docker 上的 Artisan 推荐方式

Laravel 5.2 身份验证不起作用

如何在 Laravel 中使用旧输入重定向?

Laravel - 更新时禁用更新时间

如何将对象(模型类型对象)插入到 Laravel 中特定索引号的集合对象中?

在 Laravel 5.4 中向多个抄送收件人发送Electron邮件

Laravel 验证 pdf mime

Laravel 字符串验证以允许空字符串

如何在 Laravel 测试中禁用选定的中间件