Soft delete on a intermediate table for many-to-many relationship

前端 未结 3 991
孤独总比滥情好
孤独总比滥情好 2020-12-12 22:35

How do I set soft delete on an intermediate table which is connecting two different types of entities? I\'ve added deleted_at column, but the docs say that I need to put th

3条回答
  •  Happy的楠姐
    2020-12-12 23:30

    You can put a constraint on the Eager Load:

    public function groups()
        {
    
            return $this
            ->belongsToMany('Group')
            ->whereNull('group_user.deleted_at') // Table `group_user` has column `deleted_at`
            ->withTimestamps(); // Table `group_user` has columns: `created_at`, `updated_at`
    
        }
    

    Instead of HARD deleting the relationship using:

    User::find(1)->groups()->detach();
    

    You should use something like this to SOFT delete instead:

    DB::table('group_user')
        ->where('user_id', $user_id)
        ->where('group_id', $group_id)
        ->update(array('deleted_at' => DB::raw('NOW()')));
    

提交回复
热议问题