简体   繁体   English

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

[英]Deleting related records in Laravel 5.1 (Eloquent ORM)

I have customers model, which hasMany Locations , and Locations hasMany contacts . 我有客户模型,其中有多个地点 ,而且地点有很多 联系人

I want to delete the Customer and all its locations and contacts. 我想删除客户及其所有位置和联系人。

Now below code removes the locations successfully : 现在,下面的代码成功删除了位置:

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

But I want to remove the Contacts as well. 但我也想删除联系人。

Ideally I want the code like : 理想情况下,我希望代码如下:

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

Is it possible?? 可能吗??

You could set this up in your migrations by specifying the onDelete('cascade') in your pivot table, take a look at foreign-key-constraints , eg : 您可以通过在数据透视表中指定onDelete('cascade')在迁移中进行设置,查看外键约束 ,例如:

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

Or use eloquent events , what you want in this case is the "deleting" event to do the cleanup. 或者使用雄辩的事件 ,在这种情况下你想要的是“删除”事件来进行清理。

Customer Model : 客户模型:

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

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

Location Model : 位置型号:

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

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

Hopet this helps. 希望这会有所帮助。

You Could define this in your Models. 您可以在模型中定义它。

Customer Model 客户模型

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...
        });
    }
}

And in your Locations Model 并在您的位置模型中

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...
            });
        }
    }

And Now 现在

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

Should do the trick. 应该做的伎俩。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM