简体   繁体   English

laravel一对多记录插入和更新解决方案

[英]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. 我有两个表,一个是“ ITEM”,第二个是mysql数据库中的“复合项”。 I am trying to insert multiple items id in composite item table for one single record in laravel. 我正在尝试在laravel中的单个记录的复合项目表中插入多个项目ID。

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. 我试图将多个项目ID保存为逗号分隔的值(例如“ 1,2,3,4”),并且还将该字段更新为同一概念,这是我的逻辑之一。 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. 如果我从项目表中删除任何项目,如何从复合项目表中的字符串项目ID中删除同一项目。 for example from item table i have deleted item id 3. 例如从项目表中,我已删除项目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 . 你肯定找许多一对多的关系,而不是one-to-many Laravel has excellent features for generating and maintaining a many-to-many relationship. Laravel具有出色的功能,可以生成和维护many-to-many关系。

  • The attach/detach methods are used for single or multiple insertion or deletion in a relation. attach/detach方法用于关系中的单个或多个插入或删除。 For example, if you want to add an array of items([1,2]) to a composite item, you can use attach like: 例如,如果要向复合项目添加项目数组[[1,2]),则可以使用attach如:

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

    Same goes for detaching: 分离也是如此:

      $compositeItem->items()->detach([1,2]); 
  • The sync method is used for updating existing records. sync方法用于更新现有记录。 Sync is a bit tricky and work exactly like: Sync有点棘手,其工作原理完全相同:

    The sync method accepts an array of IDs to place on the intermediate table. sync方法接受一组ID放置在中间表上。 Any IDs that are not in the given array will be removed from the intermediate table. 给定数组中没有的任何ID将从中间表中删除。

    Like if you want to remove 2 and insert 3 you can use sync like this: 就像您要删除2并插入3一样,您可以像这样使用sync

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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