Laravel - 如何预先加载自定义中间体的关系 table

Laravel - how to eager load relation of custom intermediate table

我有三个模型,SalesReturn、Product 和 ProductSalesReturn,它们之间的关系如下:

class SalesReturn extends Model
{
    public function products()
    {
        return $this->belongsToMany(Product::class)
            ->withTimestamps()
            ->using(ProductSalesReturn::class);
    }
}

我用ProductSalesReturn表示中间的table(https://laravel.com/docs/6.x/eloquent-relationships#defining-custom-intermediate-table-models),ProductSalesReturnUnit有关系:

class ProductSalesReturn extends Pivot
{
    public function unit()
    {
        return $this->belongsTo(Unit::class);
    }
}

当我急于加载 unit 关系时,如下代码:

SalesReturn::with(['products', 'products.unit'])->find($id);

我会得到以下错误:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'units.product_id' in 'where clause' (SQL: select * from `units` where `units`.`product_id` in (1031, 1631, 13391, 14361, 16981, 17441, 41982, 45982, 55741) and `units`.`deleted_at` is null)

table 模式如下:

CREATE TABLE `sales_returns` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `number` varchar(20) COLLATE utf8mb4_unicode_ci NOT NULL,
  `user_id` bigint(20) NOT NULL,
  `order_id` bigint(20) NOT NULL,
  `note` text COLLATE utf8mb4_unicode_ci NOT NULL,
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `product_sales_return` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `sales_return_id` bigint(20) NOT NULL,
  `product_id` bigint(20) NOT NULL,
  `unit_id` bigint(20) NOT NULL,
  `price` double NOT NULL,
  `amount` int(11) NOT NULL,
  `gross_profit` double NOT NULL DEFAULT '0',
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

如何在 Laravel 中预先加载自定义中间体 table 的关系?

谢谢。

您可以使用 Laravel Eloquent: Eager Load Pivot Relations

安装

composer require ajcastro/eager-load-pivot-relations

配置

use AjCastro\EagerLoadPivotRelations\EagerLoadPivotTrait;
class Product extends Model
{
    // Use the trait here to override eloquent builder.
    // It is used in this model because it is the relation model defined in
    // SalesReturn::products() relation.
    use EagerLoadPivotTrait;
}

用法

return SalesReturn::with('products.pivot.unit')->get();

Define the table, foreignPivotKey and relatedPivotKey paramethers in your produtcts belongsToMany relationship