belongsToMany relationship between same model entries
Hello, I'm a new user of filament, already loving the capabilities, the only thing that seems to have gotten more difficult is relationship management when doing data entries.
In my case:
There is a Product model. A Product has a belongsToMany relationship with other Products. We call this relationship "relatedProducts".
There is also a "products_related" table that holds the "parent_id" and "child_id". So that when I display the product with id=1 (parent_id), the client can also see the related products(id=2,4,6,9) .
Here is the relationship: (Models/Product.php)
public function relatedProducts(){
return $this->belongsToMany(Product::class, 'product_related', 'parent_id', 'child_id')->withPivot('parent_id');
}
The Migrtion:
Schema::create('product_related', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('parent_id');
$table->unsignedBigInteger('child_id');
$table->timestamps();
})
I have made a relationManager for that called "RelatedProductsRelationManager.php"
The table (after i have populated the DB table "product_related" manually) works fine. It detaches entries nicely, too.
What i cannot seem to understand is how to make the form work, and be able to select already existing products to attach.
Taken from the RelatedProductsRelationManager.php file:
protected static string $relationship = 'relatedProducts';
public function form(Form $form): Form
{
return $form
->schema([
Forms\Components\Select::make('related_product')->preload()
->options(function (RelationManager $livewire): array {
return Product::pluck('name', 'id')
->toArray();
})
]);
}
public function table(Table $table): Table
{
....
}
}
1 Reply
Update:
Ok so I was getting the error that there was a call to /App/Models/Product::products() function, when in the form of this relationship.
Which is weird, because i have specifically named my relationship "relatedProducts()" and not "products()"
I changed the relationship function to "products()" and then all good.
Any guesses why it assumed that it had to call products() ?