Synchronizing a one-to-many relationship in Laravel

后端 未结 5 728
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-06 23:51

    Another manual sync process :

    Add Model

    class Post extends Model
    {
        protected $fillable = ["name"];
    
        function links()
        {
            return $this->hasMany("App\Link");
        }
    }
    
    class Link extends Model
    {
        protected $fillable = ["name", "post_id"];
    
        function post()
        {
            return $this->belongsTo("App\Post");
        }
    }
    
    class PostLink extends Model
    {
        protected $fillable = ["post_id", "link_id"];
    
        function post()
        {
            return $this->belongsTo("App\Post");
        }
    
        function link()
        {
            return $this->belongsTo("App\Link");
        }
    }
    

    Here we go

    // list ids from request
    $linkIds = $request->input("link");
    if (!empty($linkIds))
    {
        // delete removed id from list in database
        PostLink::where('post_id','=', $post->id)->whereNotIn('post_id', $linkIds)->delete();
        // list remain id in database
        $postLinkIds = $post->links()->pluck('post_id')->toArray();
        // remove ids that already on db
        $linkIds = array_diff($linkIds, $postLinkIds);
        // check if still have id that must be save
        if (!empty($linkIds))
        {
            foreach ($linkIds as $id)
            {
                // save id to post
                $post->links()->create(['post_id' => $id]);
            }
        }
    }
    

提交回复
热议问题