[英]Deleting related records in Laravel 5.1 (Eloquent ORM)
我有客戶模型,其中有多個地點 ,而且地點有很多 聯系人 。
我想刪除客戶及其所有位置和聯系人。
現在,下面的代碼成功刪除了位置:
$customer = Customer::find($id);
$customer->locations()->delete();
但我也想刪除聯系人。
理想情況下,我希望代碼如下:
$customer->locations()->contacts()->delete();
可能嗎??
您可以通過在數據透視表中指定onDelete('cascade')
在遷移中進行設置,查看外鍵約束 ,例如:
$table->foreign('customer_id')->references('id')->on('customers')->onDelete('cascade');
$table->foreign('location_id')->references('id')->on('locations')->onDelete('cascade');
或者使用雄辯的事件 ,在這種情況下你想要的是“刪除”事件來進行清理。
客戶模型:
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();
});
}
}
希望這會有所幫助。
您可以在模型中定義它。
客戶模型
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();
應該做的伎倆。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.