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

前端 未结 3 988
孤独总比滥情好
孤独总比滥情好 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条回答
  •  天涯浪人
    2020-12-12 23:17

    You could also use Laravel's Eloquent BelongsToMany method updateExistingPivot.

    $model->relation->updateExistingPivot($relatedId, ['deleted_at' => Carbon\Carbon::now()]);
    

    So to use @RonaldHulshof examples you have a User model with a groups relationship which is a belongsToMany relationship.

    public function groups() {
        return $this->belongsToMany(Group::class)->whereNull('groups_users.deleted_at')->withTimestamps();
    }
    

    Then in order to soft delete the pivot table entry you would do the following.

    $user->groups->updateExistingPivot($groupId, ['deleted_at' => Carbon\Carbon::now()]);
    

提交回复
热议问题