2016-03-08 71 views
3

相关记录我客户模型,该模型的hasMany 位置,并位置的hasMany 接触删除在Laravel 5.1(雄辩ORM)

我想删除客户及其所有位置和联系人。

现在下面的代码成功删除地点:

$customer = Customer::find($id); 
$customer->locations()->delete(); 

但我想删除联系人为好。

理想我想喜欢代码:

$customer->locations()->contacts()->delete(); 

是否有可能?

回答

0

您可以通过在数据透视表中指定onDelete('cascade')在迁移过程中设置的,看看foreign-key-constraints,如:

$table->foreign('customer_id')->references('id')->on('customers')->onDelete('cascade'); 
$table->foreign('location_id')->references('id')->on('locations')->onDelete('cascade'); 

或者使用eloquent events,你想要什么在这种情况下,是执行清理的“删除”事件。

客户型号:

class Customer extends Eloquent 
{ 
    protected static function boot() { 
     parent::boot(); 

     static::deleting(function($customer) { 
      $customer->locations()->delete(); 
     }); 
    } 
} 

选址模型:

class Location extends Eloquent 
{ 
    protected static function boot() { 
     parent::boot(); 

     static::deleting(function($location) { 
      $location->contacts()->delete(); 
     }); 
    } 
} 

Hopet这会有所帮助。

+0

我知道外键约束,但我只想在代码级别处理它,因为这些约束会降低性能。 –

0

你可以在你的模型中定义这个。

客户型号

class Customer extends Eloquent 
{ 
    public function locations() 
    { 
     return $this->has_many('Location'); 
    } 

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

     static::deleting(function($customer) { 
      // before delete() method call this 
      $customer->locations()->delete(); 
      // do the locations cleanup... 
     }); 
    } 
} 

而在你的位置型号

class Location extends Eloquent 
    { 
     public function contacts() 
     { 
      return $this->has_many('Contact'); 
     } 

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

      static::deleting(function($location) { 
       // before delete() method call this 
       $location->contacts()->delete(); 
       // do the contacts cleanup... 
      }); 
     } 
    } 

而且现在

$customer = Customer::find($id); 
$customer->delete(); 

应该做的伎俩。

+0

它不起作用,因为它只删除了位置,而不是位置联系人。我认为它只适用于一对多的关系,在我的情况下,客户有很多位置,每个位置都有多个联系人。 –