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 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀