dongyuluan7494 2014-11-29 16:37
浏览 327
已采纳

在Laravel中同步一对多关系

If I have a many-to-many relationship it's super easy to update the relationship with its sync method.

But what would I use to synchronize a one-to-many relationship?

  • table posts: id, name
  • table links: id, name, post_id

Here, each Post can have multiple Links.

I'd like to synchronize the links associated with a specific post in the database, against an inputted collection of links (for example, from a CRUD form where I can add, remove, and modify links).

Links in the database that aren't present in my input collection should be removed. Links that exist in the database and in my input should be updated to reflect the input, and links that are only present in my input should be added as new records in the database.

To summarize the desired behavior:

  • inputArray = true / db = false ---CREATE
  • inputArray = false / db = true ---DELETE
  • inputArray = true / db = true ----UPDATE
  • 写回答

3条回答 默认 最新

  • dongpao1083 2014-11-29 16:56
    关注

    Unfortunately there is no sync method for one-to-many relations. It's pretty simple to do it by yourself. At least if you don't have any foreign key referencing links. Because then you can simple delete the rows and insert them all again.

    $links = array(
        new Link(),
        new Link()
    );
    
    $post->links()->delete();
    $post->links()->saveMany($links);
    

    If you really need to update existing one (for whatever reason) you need to do exactly what you described in your question.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?