dongshi8038 2017-02-17 20:47
浏览 44
已采纳

Laravel - 无法在多对多关系中找到()附加对象

in my POST form users are able to add other users to a room. I put a unique constraint on the link (no duplicate entry in the link between users and rooms). However when I refresh my page (f5) after submitting the form, Laravel complains about duplicate entries, although I do check if the objects are attached before.

Here's the code:

$roomUsers = Room::find($request->room_id)->users();

if ($request->add != null) {
    foreach ($request->add as $uId)
        // if null, user hasnt been attach yet
        if (!$roomUsers->find($uId)) {
            Log::debug($roomUsers->find($uId) == null ? 'null' : 'not null');
            // then we can attach him
            $roomUsers->attach($uId);
        }
}

The line !$roomUsers->find($uId) returns true yet the object has been attached in the previous iteration. How is that possible ? Thanks

  • 写回答

1条回答 默认 最新

  • ds20021205 2017-02-19 13:43
    关注

    The reason you're above code isn't working is because you're not creating a new instance of BelongsToMany for each check. This means that every time you call find you're not actually creating a new query you're just adding to the existing one e.g.

    say you the ids to add are [1, 2, 3] by the last check your query would effectively be:

    SELECT * FROM users WHERE id = 1 AND id = 2 AND id = 3
    

    To keep with the above logic you could do:

    $room = Room::find($request->room_id);
    
    if ($request->add != null) {
        foreach ($request->add as $uId)
            // if null, user hasnt been attach yet
            if (!$room->users()->find($uId)) {
                // then we can attach him
                $room->users()->attach($uId);
            }
    }
    

    Or a much simpler way to go about this would be to syncWithoutDetaching.

    Your code could then look something like:

    $roomUsers = Room::find($request->room_id);
    
    if ($request->has('add')) {
        $roomUsers->users()->syncWithoutDetaching($request->add);
    }
    

    Hope this helps!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程