简体   繁体   中英

laravel one to many record insert and update solution

I have two tables one is "ITEM" and second one is "Composite Item" in mysql database. I am trying to insert multiple items id in composite item table for one single record in laravel.

One of logic I have tried to save multiple items id as comma separated value for example "1,2,3,4" and also update that one field as same concept. but I am having issue when i delete any one item from item table. if i delete any of the item from item table how can i delete that same item from string item ids in composite item table. for example from item table i have deleted item id 3.

also i have think if i create new table for one to many relation then how can i update record when i update record.

You are definitely looking for many-to-many relationships, not one-to-many . Laravel has excellent features for generating and maintaining a many-to-many relationship.

  • The attach/detach methods are used for single or multiple insertion or deletion in a relation. For example, if you want to add an array of items([1,2]) to a composite item, you can use attach like:

      $compositeItem->items()->attach([1,2]); 

    Same goes for detaching:

      $compositeItem->items()->detach([1,2]); 
  • The sync method is used for updating existing records. Sync is a bit tricky and work exactly like:

    The sync method accepts an array of IDs to place on the intermediate table. Any IDs that are not in the given array will be removed from the intermediate table.

    Like if you want to remove 2 and insert 3 you can use sync like this:

     $compositeItem->items()->sync([1,3]); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM