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

3
我有一个客户模型,其中有许多位置,并且这些位置又有许多联系人。
我想删除该客户及其所有位置和联系人。
现在下面的代码可以成功删除位置:
$customer = Customer::find($id);
$customer->locations()->delete();

但是我也想移除联系人。

理想情况下,我希望代码像这样:

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

这是可能的吗?

2个回答

0

您可以在迁移中通过在您的关联表中指定 onDelete('cascade') 来设置它,请参阅外键约束,例如:

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

或者使用 Eloquent 事件,在这种情况下,您想要的是“删除”事件来进行清理。

客户模型:

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

希望这能有所帮助。

我知道外键约束,但我只想在代码层面上处理它,因为这些约束会降低性能。 - Adnan Tahir Hashmi
我已经尝试过了,但子模型没有工作 :( - Ray Coder

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

应该可以解决问题。


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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接