Form builder - trying to create/edit relationship with pivot
Hello all!
I'm trying to, as the title states, edit a relationship with a pivot table.
Here are the relevant code snippets:
Artist:
public function events()
{
return $this->belongsToMany(MusicEvent::class,'music_event_artist','artist_id','music_event_id')
->withPivot("id","artist_id","music_event_id")
->using(EventArtist::class);
}
MusicEvent:
public function artists()
{
return $this->belongsToMany(Artist::class,'music_event_artist','music_event_id','artist_id')
->withPivot("id","artist_id","music_event_id")
->using(EventArtist::class);
}
EventArtist:
class EventArtist extends Pivot
{
public $table = "music_event_artist";
protected $fillable = ['artist_id','music_event_id'];
}
ArtistsRelationManager:
protected static string $relationship = 'artists';
return $form
->schema([
Forms\Components\Select::make('artists')
->label('Event Artist')
->options(Artist::orderBy('name')->get()->pluck('name','id'))
->searchable(),
]);
It then attempts to CRUD an Artist object instead of EventArtist (although the form data isn't used in the query.)
Duplicate entry '' for key 'code'
insert into
artists () values ()
In tinker, things work as expected.
$e = MusicEvent::find(1234);
= App\Models\MusicEvent {#7128
id: 1234,
description: "Test data here",
artists: Collection {#7106
all: [
App\Models\Artist (etc),
pivot: App\Models\EventArtist...
},
],
},
}
$e2 = Artist::find($e->artists[0]->id);
= App\Models\Artist {#7108
id: 6789,
code: "jado",
name: "Jane Doe",
}
And the reverse (artist events) query works as expected too.
Hopefully all this should adequately describe the environment. Any help would be very greatly appreciated!Solution:Jump to solution
If this helps anyone, the solution was to use AttachAction instead of CreateAction.
1 Reply
Solution
If this helps anyone, the solution was to use AttachAction instead of CreateAction.