Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[8.x] Add eager loading of pivot relations #37456

Closed
wants to merge 10 commits into from
Closed
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 59 additions & 0 deletions src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php
Original file line number Diff line number Diff line change
Expand Up @@ -789,12 +789,71 @@ public function get($columns = ['*'])
// have been specified as needing to be eager loaded. This will solve the
// n + 1 query problem for the developer and also increase performance.
if (count($models) > 0) {
$pivotEagerLoad = $this->getPivotEagerLoads($builder);

if (! empty($pivotEagerLoad)) {
$this->eagerLoadPivotRelations($models, $pivotEagerLoad);
}

$models = $builder->eagerLoadRelations($models);
}

return $this->related->newCollection($models);
}

/**
* Get the pivot eager load relations.
*
* @param \Illuminate\Database\Eloquent\Builder $builder
* @return array
*/
protected function getPivotEagerLoads($builder)
{
// Only return the eagerLoad `pivot.*` but not the `pivot`
$pivotEagerLoad = array_filter($builder->getEagerLoads(), function ($relation) {
return Str::startsWith($relation, $this->accessor.'.');
}, ARRAY_FILTER_USE_KEY);

$builder->without(array_merge(
[$this->accessor], // we make sure to also remove the `pivot` in the eagerLoad
array_keys($pivotEagerLoad)
));

return $pivotEagerLoad;
}

/**
* Eager load the relations of the pivot of the models.
*
* @param array $models
* @param array $eagerLoad
* @return void
*/
protected function eagerLoadPivotRelations(array $models, array $eagerLoad)
{
$pivots = \Illuminate\Support\Arr::pluck($models, $this->accessor);
$eagerLoad = $this->removePivotFromEagerLoadKeys($eagerLoad);
$builder = head($pivots)->query();
$builder->with($eagerLoad)->eagerLoadRelations($pivots);
}

/**
* Remove the `pivot.` part of the eager load relations.
*
* @param array $eagerLoad
* @return array
*/
protected function removePivotFromEagerLoadKeys(array $eagerLoad)
{
$newEagerLoad = [];
foreach ($eagerLoad as $name => $callback) {
$name = str_replace($this->accessor.'.', '', $name);
ajcastro marked this conversation as resolved.
Show resolved Hide resolved
$newEagerLoad[$name] = $callback;
}

return $newEagerLoad;
}

/**
* Get the select columns for the relation query.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -511,6 +511,8 @@ public function newPivot(array $attributes = [], $exists = false)
$this->parent, $attributes, $this->table, $exists, $this->using
);

$pivot->preventsLazyLoading = Pivot::preventsLazyLoading();

return $pivot->setPivotKeys($this->foreignPivotKey, $this->relatedPivotKey);
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,194 @@
<?php

namespace Illuminate\Tests\Integration\Database\EloquentBelongsToManyEagerLoadPivotRelationsTest;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\Pivot;
use Illuminate\Database\LazyLoadingViolationException;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Str;
use Illuminate\Tests\Integration\Database\DatabaseTestCase;

/**
* @group integration
*/
class EloquentBelongsToManyEagerLoadPivotRelationsTest extends DatabaseTestCase
{
protected function setUp(): void
{
parent::setUp();

Schema::create('employees', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});

Schema::create('deductions', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});

Schema::create('payroll_periods', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});

Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});

Schema::create('employees_deductions', function (Blueprint $table) {
$table->foreignId('employee_id');
$table->foreignId('deduction_id');
$table->foreignId('payroll_period_id');
$table->foreignId('user_id')->nullable();
$table->decimal('amount', 8, 2)->default(0);
$table->timestamps();
});
}

public function tearDown(): void
{
parent::tearDown();
Model::preventLazyLoading(false);
}

public function testCanEagerLoadPivotRelations()
{
$employee = Employee::create(['name' => Str::random()]);
$deduction = Deduction::create(['name' => Str::random()]);
$payrollPeriod = PayrollPeriod::create(['name' => Str::random()]);
$employee->deductions()->attach($deduction->id, [
'payroll_period_id' => $payrollPeriod->id,
'amount' => 100,
]);

$employee = Employee::with('deductions.pivot.payrollPeriod')->get()->first();

$pivot = $employee->deductions->first()->pivot;

$this->assertTrue($pivot->relationLoaded('payrollPeriod'));

$this->assertInstanceOf(PayrollPeriod::class, $pivot->payrollPeriod);
}

public function testCanEagerLoadManyPivotRelations()
{
$employee = Employee::create(['name' => Str::random()]);
$deduction = Deduction::create(['name' => Str::random()]);
$payrollPeriod = PayrollPeriod::create(['name' => Str::random()]);
$user = User::create(['name' => Str::random()]);
$employee->deductions()->attach($deduction->id, [
'payroll_period_id' => $payrollPeriod->id,
'user_id' => $user->id,
'amount' => 100,
]);

$employee = Employee::with([
'deductions.pivot.payrollPeriod',
'deductions.pivot.user',
])->get()->first();

$pivot = $employee->deductions->first()->pivot;

$this->assertTrue($pivot->relationLoaded('payrollPeriod'));
$this->assertInstanceOf(PayrollPeriod::class, $pivot->payrollPeriod);

$this->assertTrue($pivot->relationLoaded('user'));
$this->assertInstanceOf(User::class, $pivot->user);
}

public function testAccessOnPivotRelationsWillThrowLazyLoadingViolationExceptionIfNotEagerLoaded()
{
$this->expectException(LazyLoadingViolationException::class);
$this->expectExceptionMessage('Attempted to lazy load');

$employee = Employee::create(['name' => Str::random()]);
$deduction = Deduction::create(['name' => Str::random()]);
$payrollPeriod = PayrollPeriod::create(['name' => Str::random()]);
$employee->deductions()->attach($deduction->id, [
'payroll_period_id' => $payrollPeriod->id,
'amount' => 100,
]);

Model::preventLazyLoading();

$employee->deductions()->get()->first()->pivot->payrollPeriod;
}

public function testAccessOnPivotRelationsWillBeOkayIfEagerLoaded()
{
$employee = Employee::create(['name' => Str::random()]);
$deduction = Deduction::create(['name' => Str::random()]);
$payrollPeriod = PayrollPeriod::create(['name' => Str::random()]);
$employee->deductions()->attach($deduction->id, [
'payroll_period_id' => $payrollPeriod->id,
'amount' => 100,
]);

Model::preventLazyLoading();

$employee->deductions()->with('pivot.payrollPeriod')->get()->first()->pivot->payrollPeriod;
}
}

class Employee extends Model
{
public $table = 'employees';
public $timestamps = true;
protected $guarded = [];

public function deductions()
{
return $this->belongsToMany(Deduction::class, 'employees_deductions')
->withTimestamps()
->withPivot([
'payroll_period_id',
'user_id',
'amount',
])
->using(EmployeeDeduction::class);
}
}

class Deduction extends Model
{
public $table = 'deductions';
public $timestamps = true;
protected $guarded = [];
}

class PayrollPeriod extends Model
{
public $table = 'payroll_periods';
public $timestamps = true;
protected $guarded = [];
}

class User extends Model
{
public $table = 'users';
public $timestamps = true;
protected $guarded = [];
}

class EmployeeDeduction extends Pivot
{
protected $table = 'employees_deductions';

public function payrollPeriod()
{
return $this->belongsTo(PayrollPeriod::class);
}

public function user()
{
return $this->belongsTo(User::class);
}
}