Skip to content

Commit f0fe493

Browse files
Merge pull request #85 from saade/fix/belongs-to-relationship
fix BelongsTo relationship
2 parents f6bf2f6 + d793be4 commit f0fe493

File tree

1 file changed

+25
-6
lines changed

1 file changed

+25
-6
lines changed

src/SelectTree.php

Lines changed: 25 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -93,19 +93,38 @@ protected function setUp(): void
9393

9494
// Set the component's state with the extracted IDs.
9595
$component->state($state);
96+
97+
return;
98+
}
99+
100+
/** @var BelongsTo $relationship */
101+
if (! $relatedModel = $relationship->getResults()) {
102+
return;
96103
}
104+
105+
$component->state(
106+
$relatedModel->getAttribute(
107+
$relationship->getOwnerKeyName(),
108+
),
109+
);
97110
});
98111

99112
// Save relationships using a callback function.
100113
$this->saveRelationshipsUsing(static function (self $component, $state) {
101-
// Check if the component's relationship is a BelongsToMany relationship.
102-
if ($component->getRelationship() instanceof BelongsToMany) {
103-
// Wrap the state in a collection and convert it to an array if it's not set.
104-
$state = Collection::wrap($state ?? []);
114+
$relationship = $component->getRelationship();
115+
116+
// Check if the component's relationship is a BelongsTo relationship.
117+
if ($relationship instanceof BelongsTo) {
118+
$relationship->associate($state)->save();
105119

106-
// Sync the relationship with the provided state (IDs).
107-
$component->getRelationship()->sync($state->toArray());
120+
return;
108121
}
122+
123+
// Wrap the state in a collection and convert it to an array if it's not set.
124+
$state = Collection::wrap($state ?? []);
125+
126+
// Sync the relationship with the provided state (IDs).
127+
$component->getRelationship()->sync($state->toArray());
109128
});
110129

111130
$this->createOptionUsing(static function (SelectTree $component, array $data, Form $form) {

0 commit comments

Comments
 (0)