具有级联删除功能的事务管理的Laravel Soft Delete

时间:2019-04-15 08:20:55

标签: laravel

场景:          学生->父母,          学生儿童班
           父母:学生
           子:标记                          地址
           大孩子主要地址                            辅助地址

   We are using the Cascade Soft-Delete for the above scenario with the code below : 

这里发生了多次删除,需要建议以了解是否必须为级联删除添加事务管理。

 use Illuminate\Database\Eloquent\SoftDeletes;

 class Student extends Model
  {
   use SoftDeletes;

   protected static function boot()
   {
    parent::boot();

    static::deleting(function ($student) {
        foreach ([
            'address',
            'mark'
        ] as $relation) {
            foreach ($student->{$relation} as $item) {
                $item->delete();
            }
        }
    });
  }

 public function address()
   {
    return $this->hasMany(StudentAddress::class, 'student');
    }

  public function mark()
   {
    return $this->hasMany(Marks::class, 'mark_detail');
   }
 }

1 个答案:

答案 0 :(得分:0)

要在Laravel中添加交易,请检查以下代码

\DB::transaction(function () {
      Your queried goes here
});

DB::beginTransaction();
     Your queried goes here
DB::commit();