donglun1020 2013-08-11 00:42
浏览 4
已采纳

是否有任何方法可以编辑多对多的关系,而无需在Laravel中进行附加分离

After spending hours and following the code, I found that Laravel has no way of Editing The Intermediate table in Many To Many Relation without detaching and attaching .. This is okay but it has a big disadvantage. Applying the app on big scale, the id index increases rapidly. So I wonder if there are anyway ? And how to overcome this ID problems (I though about cron jobs to reindex it)

  • 写回答

1条回答 默认 最新

  • duanlaiyin2356 2013-08-11 04:06
    关注

    Of course there is! Suppose you have this database structure, where User and Group share a many-to-many relationship, with a valid field in the pivot (intermediary) table.

    +-------------+  +-------------+  +-------------+
    | users       |  | groups      |  | group_user  |
    +-------------+  +-------------+  +-------------+
    | id          |  | id          |  | group_id    |
    | name        |  | name        |  | user_id     |
    | email       |  | desc        |  | valid       |
    +-------------+  +-------------+  +-------------+
    

    Now, since the valid column is not strictly necessary for the relationship, you'll have to tell Laravel to specifically fetch this row. For the sake of simplicity, I'll call it right in the example, but if you need it very often, you'd probably want to put that in the model relationship itself, on User.groups and Group.users methods.

    // Retrive the user with ID one
    $user = User::find(1);
    
    // This tells Laravel to fetch the `valid` column, when
    // the user's groups
    $userGroups = $user->groups()->withPivot('valid')->get();
    
    // Get the first group
    $firstGroup  = $userGroups->first();
    
    // Change the `valid` value for that first group
    $firstGroup->pivot->valid = true;
    
    // Save the changes
    $firstGroup->pivot->save();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作