Synchronizing a one-to-many relationship in Laravel

后端 未结 5 606
Happy的楠姐
Happy的楠姐 2021-02-06 23:17

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 re

5条回答
  •  一生所求
    2021-02-07 00:06

    I did like this, and it is optimized for minimal query and minimal updates:

    first, put link ids to sync in an array: $linkIds and the post model in its own variable: $post

    Link::where('post_id','=',$post->id)->whereNotIn('id',$linkIds)//only remove unmatching
        ->update(['post_id'=>null]);
    if($linkIds){//If links are empty the second query is useless
        Link::whereRaw('(post_id is null OR post_id<>'.$post->id.')')//Don't update already matching, I am using Raw to avoid a nested or, you can use nested OR
            ->whereIn('id',$linkIds)->update(['post_id'=>$post->id]);
    }
    

提交回复
热议问题