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 CreateBitmapFromWicBitmap内存释放问题。
  • ¥30 win c++ socket
  • ¥15 CanMv K210开发板实现功能
  • ¥15 C# datagridview 栏位进度
  • ¥15 vue3页面el-table页面数据过多
  • ¥100 vue3中融入gRPC-web
  • ¥15 kali环境运行volatility分析android内存文件,缺profile
  • ¥15 写uniapp时遇到的问题
  • ¥15 vs 2008 安装遇到问题
  • ¥15 matlab有限元法求解梁带有若干弹簧质量系统的固有频率