繁体   English   中英

Laravel - 如何急切加载自定义中间表的关系

[英]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来表示中间表( 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)

表模式如下:

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

谢谢你。

您可以使用Laravel Eloquent:急切加载 Pivot 关系

安装

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

在您的produtcts关系中定义tableforeignPivotKeyrelatedPivotKey belongsToMany

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM