Search code examples
phplaraveleloquenteager-loading

Laravel - how to eager load relation of custom intermediate table


I have three models, SalesReturn, Product and ProductSalesReturn, and their relations are following:

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

I use the ProductSalesReturn to represent the intermediate table ( https://laravel.com/docs/6.x/eloquent-relationships#defining-custom-intermediate-table-models ), and ProductSalesReturn has a relation to Unit:

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

When I eager loading the unit relation like following code:

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

I will get the following error:

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)

The table schemas are following:

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;

How can I eager loading the relation of custom intermediate table in Laravel ?

Thank you.


Solution

  • You could use Laravel Eloquent: Eager Load Pivot Relations

    Installation

    composer require ajcastro/eager-load-pivot-relations
    

    Configuration

    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;
    }
    

    Usage

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

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