Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
7 changes: 6 additions & 1 deletion src/Phaseolies/Database/Entity/Model.php
Original file line number Diff line number Diff line change
Expand Up @@ -1019,6 +1019,7 @@ public function __get($name)

case 'bindToMany':
$relatedModel = app($this->getLastRelatedModel());
$relatedModelClass = get_class($relatedModel);
$pivotColumns = app('db')->getTableColumns($this->getLastPivotTable());
$pivotTable = $this->getLastPivotTable();
$pivotSelects = array_map(function ($column) use ($pivotTable) {
Expand Down Expand Up @@ -1050,7 +1051,11 @@ public function __get($name)
$result->pivot = $pivotObj;
$grouped[$pivot[$this->getLastForeignKey()]][] = $result;
}
$this->setRelation($name, $grouped);

$this->setRelation(
$name,
new Collection($relatedModelClass, $grouped[$this->getKey()] ?? [])
);

return $results;
}
Expand Down
7 changes: 5 additions & 2 deletions tests/Model/Query/EntityModelQueryBehavior.php
Original file line number Diff line number Diff line change
Expand Up @@ -2563,12 +2563,15 @@ public function testPostTagRelateMethod()
$post = MockPost::find(1);
$post->tags()->relate([1, 2, 3]);
$this->assertEquals([1, 2, 3], $post->tags->pluck('id')->sort()->values()->toArray());
$this->assertCount(1, $post->tags);
$this->assertCount(3, $post->tags);

$changes = $post->tags()->relate([1, 2, 4]);
$this->assertEquals([4], array_keys($changes['attached']));
$this->assertEquals([2], array_keys($changes['detached']));
$this->assertEquals([3], array_values($changes['detached']));
$this->assertEquals([], $changes['updated']);

$post = MockPost::find(1);
$this->assertEquals([1, 2, 4], $post->tags->pluck('id')->sort()->values()->toArray());
}

public function testRepairMethodFetchingRecords()
Expand Down
18 changes: 18 additions & 0 deletions tests/Model/Query/EntityRelationshipBehavior.php
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,24 @@ public function testBindToManyLazyLoadSingleTag(): void
$this->assertEquals('Database', $tags[0]->name);
}

/**
* Re-reading a lazy bindToMany relation should return the cached collection,
* not the internal grouped array keyed by the pivot foreign key.
*/
public function testBindToManyLazyLoadCachesCollectionForRepeatedAccess(): void
{
$post = MockPost::find(1);

$firstRead = $post->tags;
$secondRead = $post->tags;

$this->assertInstanceOf(Collection::class, $firstRead);
$this->assertInstanceOf(Collection::class, $secondRead);
$this->assertCount(2, $secondRead);
$this->assertEquals('PHP', $secondRead[0]->name);
$this->assertEquals(1, $secondRead[0]->pivot->post_id);
}

/**
* Inverse: Tag 1 (PHP) belongs to many Posts.
*/
Expand Down
Loading