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

时间:2016-03-08 15:28:56

标签: php orm eloquent laravel-5.1 relationship

我有客户型号,其中包含多个位置位置包含多个联系人

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

现在,下面的代码会成功删除位置:

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

但我也想删除联系人。

理想情况下,我希望代码如下:

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

有可能吗?

2 个答案:

答案 0 :(得分: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();
        });
    }
}

希望这有帮助。

答案 1 :(得分: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();

应该做的伎俩。