F
Filament5mo ago
Pan

Filament Demo shop_category_product, how does it work?

I've checked out the migration files of the three tables "shop_categories", "shop_category_product" and "shop_products". I've noticed that in the "shop_products" & "shop_categories" there are no foreign id field for each other but instead in the model of those two tables, they have a BelongsToMany relationship with "shop_category_product". and at that table seems to be where magic happens where it foreign id to both the primary id of "shop_products" & "shop_categories" as its primary key. What I don't understand is how it seem to still perfectly all connected by showing the categories attached to the product while in the product table there's no categories field. Like how does the "shop_category_product" table updates when a new attachment of a category on a product is added and how it is shown in the Forms of of "ProductResource.php" This seem to be the magic of the code but I can't find out how it works playing around.
Forms\Components\Select::make('categories')
->relationship('categories','name')
->multiple()
->required(),
Forms\Components\Select::make('categories')
->relationship('categories','name')
->multiple()
->required(),
2 Replies
Tieme
Tieme5mo ago
GitHub
demo/app/Models/Shop/Product.php at 20ee634df15aa0ea5e1bd26bb8442d7...
Source code for the demo.filamentphp.com website. Contribute to filamentphp/demo development by creating an account on GitHub.
Tieme
Tieme5mo ago
categories is the relation on product. In addition to customizing the name of the intermediate table, you may also customize the column names of the keys on the table by passing additional arguments to the belongsToMany method. The third argument is the foreign key name of the model on which you are defining the relationship, while the fourth argument is the foreign key name of the model that you are joining to