删除Laravel 5.1(雄辩ORM)中的相关记录


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

应该做这个伎俩。