提问者:小点点

Laravel-如何快速加载自定义中间表的关系


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

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

我使用productSalesBack来表示中间表(https://laravel.com/docs/6.x/eloquent-relationships#defining-custom-intermediate-table-models),并且productSalesBackUnit有关系:

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

当我急切地加载单元关系时,如以下代码所示:

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)

表模式如下:

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中快速加载自定义中间表的关系?

非常感谢。


共1个答案

匿名用户

您可以使用Laravel雄辩:渴望负载枢轴关系

安装

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();

定义的外PivotKey相关的PivotKey参数在你的produtcts属性