Skip to content

Commit 99aede0

Browse files
[9.x] Prevent test issues with relations with the $touches property (#45118)
* #45064 - Added function to remove empty relationships that were causing issues with touched relationships on tests * #45064 - Fixed code style issue * formatting Co-authored-by: Taylor Otwell <[email protected]>
1 parent b194985 commit 99aede0

File tree

2 files changed

+16
-0
lines changed

2 files changed

+16
-0
lines changed

src/Illuminate/Database/Eloquent/Factories/Factory.php

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -328,6 +328,12 @@ protected function store(Collection $results)
328328

329329
$model->save();
330330

331+
foreach ($model->getRelations() as $name => $items) {
332+
if ($items->isEmpty()) {
333+
$model->unsetRelation($name);
334+
}
335+
}
336+
331337
$this->createChildren($model);
332338
});
333339
}

tests/Database/DatabaseEloquentFactoryTest.php

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -356,6 +356,14 @@ public function test_belongs_to_many_relationship()
356356
unset($_SERVER['__test.role.creating-role'], $_SERVER['__test.role.creating-user']);
357357
}
358358

359+
public function test_belongs_to_many_relationship_related_models_set_on_instance_when_touching_owner()
360+
{
361+
$user = FactoryTestUserFactory::new()->create();
362+
$role = FactoryTestRoleFactory::new()->hasAttached($user, [], 'users')->create();
363+
364+
$this->assertCount(1, $role->users);
365+
}
366+
359367
public function test_belongs_to_many_relationship_with_existing_model_instances()
360368
{
361369
$roles = FactoryTestRoleFactory::times(3)
@@ -913,6 +921,8 @@ class FactoryTestRole extends Eloquent
913921
{
914922
protected $table = 'roles';
915923

924+
protected $touches = ['users'];
925+
916926
public function users()
917927
{
918928
return $this->belongsToMany(FactoryTestUser::class, 'role_user', 'role_id', 'user_id')->withPivot('admin');

0 commit comments

Comments
 (0)