From 1aeaa0094a8e357b2a633bb3ee7ec969f76b2458 Mon Sep 17 00:00:00 2001 From: Marcus Moore Date: Tue, 9 Apr 2024 13:52:54 -0700 Subject: [PATCH] Fix assigned to in labels --- app/Models/Labels/FieldOption.php | 10 ++++++-- tests/Unit/Models/Labels/FieldOptionTest.php | 26 ++++++++++++++++++++ 2 files changed, 34 insertions(+), 2 deletions(-) create mode 100644 tests/Unit/Models/Labels/FieldOptionTest.php diff --git a/app/Models/Labels/FieldOption.php b/app/Models/Labels/FieldOption.php index 7e45cc0ce7..38a90e31dc 100644 --- a/app/Models/Labels/FieldOption.php +++ b/app/Models/Labels/FieldOption.php @@ -18,8 +18,14 @@ class FieldOption { // assignedTo directly on the asset is a special case where // we want to avoid returning the property directly // and instead return the entity's presented name. - if ($dataPath[0] === 'assignedTo'){ - return $asset->assignedTo ? $asset->assignedTo->present()->fullName() : null; + if ($dataPath[0] === 'assignedTo') { + if ($asset->relationLoaded('assignedTo')) { + // If the "assignedTo" relationship was eager loaded then the way to get the + // relationship changes from $asset->assignedTo to $asset->assigned. + return $asset->assigned ? $asset->assigned->present()->fullName() : null; + } + + return $asset->assignedTo ? $asset->assignedTo->present()->fullName() : null; } return $dataPath->reduce(function ($myValue, $path) { diff --git a/tests/Unit/Models/Labels/FieldOptionTest.php b/tests/Unit/Models/Labels/FieldOptionTest.php new file mode 100644 index 0000000000..6616ab2304 --- /dev/null +++ b/tests/Unit/Models/Labels/FieldOptionTest.php @@ -0,0 +1,26 @@ +assignedToUser(User::factory()->create(['first_name' => 'Luke', 'last_name' => 'Skywalker'])) + ->create(); + + $this->assertEquals('Luke Skywalker', $fieldOption->getValue($asset)); + // If the "assignedTo" relationship was eager loaded then the way to get the + // relationship changes from $asset->assignedTo to $asset->assigned. + $this->assertEquals('Luke Skywalker', $fieldOption->getValue(Asset::with('assignedTo')->find($asset->id))); + } +}