@@ -31,6 +31,8 @@ class SelectTree extends Field
3131
3232 protected string $ titleAttribute ;
3333
34+ protected string $ parentAttribute ;
35+
3436 protected bool $ clearable = true ;
3537
3638 protected bool $ expandSelected = true ;
@@ -77,29 +79,14 @@ protected function setUp(): void
7779
7880 private function buildTree (int $ parent = null ): array |Collection
7981 {
80- // Determine the foreign key based on the type of relationship.
81- if ($ this ->getRelationship () instanceof BelongsTo) {
82- $ key = $ this ->getRelationship ()->getForeignKeyName ();
83- }
84-
85- // Determine the related pivot key for BelongsToMany relationships.
86- if ($ this ->getRelationship () instanceof BelongsToMany) {
87- $ key = $ this ->getRelationship ()->getRelatedPivotKeyName ();
88- }
89-
90- // If the key is not set, return an empty array.
91- if (! isset ($ key )) {
92- return [];
93- }
94-
9582 // Create a default query to retrieve related items.
9683 $ defaultQuery = $ this ->getRelationship ()
9784 ->getRelated ()
9885 ->query ()
99- ->where ($ key , $ parent );
86+ ->where ($ this -> getParentAttribute () , $ parent );
10087
10188 // If we're not at the root level and a modification callback is provided, apply it to the query.
102- if (! $ parent && $ this ->modifyQueryUsing ) {
89+ if (!$ parent && $ this ->modifyQueryUsing ) {
10390 $ defaultQuery = $ this ->evaluate ($ this ->modifyQueryUsing , ['query ' => $ defaultQuery ]);
10491 }
10592
@@ -121,10 +108,11 @@ private function buildTree(int $parent = null): array|Collection
121108 });
122109 }
123110
124- public function relationship (string $ relationship , string $ titleAttribute , Closure $ modifyQueryUsing = null ): self
111+ public function relationship (string $ relationship , string $ titleAttribute , string $ parentAttribute , Closure $ modifyQueryUsing = null ): self
125112 {
126113 $ this ->relationship = $ relationship ;
127114 $ this ->titleAttribute = $ titleAttribute ;
115+ $ this ->parentAttribute = $ parentAttribute ;
128116 $ this ->modifyQueryUsing = $ modifyQueryUsing ;
129117
130118 return $ this ;
@@ -147,6 +135,11 @@ public function getTitleAttribute(): string
147135 return $ this ->evaluate ($ this ->titleAttribute );
148136 }
149137
138+ public function getParentAttribute (): string
139+ {
140+ return $ this ->evaluate ($ this ->parentAttribute );
141+ }
142+
150143 public function clearable (bool $ clearable = true ): static
151144 {
152145 $ this ->clearable = $ clearable ;
0 commit comments