问题描述
我有 3 个表:accounts -> services -> service_items
当我删除帐户时,我希望删除服务以及与该服务相关的所有 service_items。
public function delete()
{
$this->services()->delete();
return parent::delete();
}
这是有效的,当帐户被删除时,所有相关的服务都被删除,但服务项目没有被删除。
我的服务模型中有以下功能
public function delete()
{
$this->service_items()->delete();
return parent::delete();
}
我删除帐户时似乎没有触发此功能。我知道我可以遍历服务并删除每个 service_item 但我想知道是否有办法在服务模型中触发删除功能?
注意:如果我直接删除服务,service_items 将被删除
解决方法
好的,这里是解决方案。 与其单独删除每个service_item,不如使用Laravel的hook的概念,在model下声明booted方法
Account.php
<?php
class Account extends Model
{
/**
* The "booted" method of the model.
*
* @return void
*/
protected static function booted()
{
static::deleted(function($account) {
$account->services()->delete();
});
}
/**
* List of services associated with an account.
*/
public function services()
{
// or you may have some other relationship
return $this->hasMany('App\Service');
}
}
Service.php
<?php
class Service extends Model
{
/**
* The "booted" method of the model.
*
* @return void
*/
protected static function booted()
{
static::deleted(function($service) {
$service->items()->delete();
});
}
/**
* List of items associated with an account.
*/
public function items()
{
// or you may have some other relationship
return $this->hasMany('App\ServiceItem');
}
}
因此,无论何时您删除一个帐户,它都会删除与该帐户关联的所有服务,进而删除与每个服务关联的所有服务项目。