Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions src/Database/Eloquent/Relations/BelongsToMany.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,49 @@ protected function addWhereConstraints()
return $this;
}

/**
* Set the constraints for an eager load of the relation.
*
* @param array $models
* @return void
*/
public function addEagerConstraints(array $models)
{
if ($this->parent->hasMutator($this->parentKey) === false) {
parent::addEagerConstraints($models);
}

$this->query->whereIn($this->getQualifiedForeignPivotKeyName(), $this->parseIds($this->getKeys($models, $this->parentKey)));
}

/**
* Build model dictionary keyed by the relation's foreign key.
*
* @param \Illuminate\Database\Eloquent\Collection $results
* @return array
*/
protected function buildDictionary(Collection $results)
{
// First we will build a dictionary of child models keyed by the foreign key
// of the relation so that we will easily and quickly match them to their
// parents without having a possibly slow inner loops for every models.
$dictionary = [];

foreach ($results as $result) {
$key = $result->{$this->accessor}->{$this->foreignPivotKey};

// If the pivots parent serializes its key, than the pivot result will also be serialized
// This means dictionary lookups will happen with a unserialized key (hex instead of binary)
// We need to build the dictionary using unserialized keys so lookups will succeed
if ($result->{$this->accessor}->pivotParent->hasMutator($this->relatedKey)) {
$key = $result->{$this->accessor}->pivotParent->unserializeAttribute($this->relatedKey, $key);
}
$dictionary[$key][] = $result;
}

return $dictionary;
}

/**
* Create a new pivot attachment record.
*
Expand Down
12 changes: 12 additions & 0 deletions tests/Integration/BelongsToManyMutatedTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,18 @@ public function testPivotRecordsGetCreated()
$modelA->testModelBs()->attach(TestModelB::all(), ['extra' => 'Something Extra']);
$this->assertEquals(2, $modelA->testModelBs()->count());
}

public function testEagerLoadRelations()
{
$idA = Uuid::uuid1()->toString();
$idB = Uuid::uuid1()->toString();
$modelA = (new TestModelA())->create(['id' => $idA, 'name' => 'A table']);
$modelB = (new TestModelB())->create(['id' => $idB, 'name' => 'B table']);
$modelA->testModelBs()->attach($modelB);

$result = TestModelA::first()->with('testModelBs')->get()->toArray();
$this->assertEquals(count($result[0]['test_model_bs']), 1);
}
}

class TestModelA extends Model
Expand Down