Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
845 views
in Technique[技术] by (71.8m points)

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

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 this into the model:

protected $softDelete = true;

Of course, I don't have a model for an intermediate table. Any idea?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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()')));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...