Touch method
1) Most of the time user update data in the child table but also wants to update the user (parent) table updated_at field.
For that, you don't need to update it manually by querying it.
Use the touch method on the model object inside controller. This method will only update the updated_at field to the current date/time.
2) You could also update field automatically, lets say where there is new comment on post and you also want to update post table updated_at feild at the same time than what you need to do
Inside Comment Model
define belongtomany relationship to post model class and also specify a protected variable
Sync() Method
This method is use to add multiple id's of data into pivot table with many to many relationship.
This method remove existing id's and add new id's.
If you want existing id's remian in the pivot table than you will use this code.
$book->authors()->syncWithoutDetaching([1, 2, 3]);
Useful links
https://blog.quickadminpanel.com/laravel-belongstomany-add-extra-fields-to-pivot-table/
https://laravel.com/docs/9.x/eloquent-relationships#many-to-many-polymorphic-relations
https://www.amitmerchant.com/attach-detach-sync-laravel/
Comments
Post a Comment