@@ -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