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
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]);
}