使用laravel删除相关行

AgeDeO

我正在尝试使用以下命令删除Laravel中的所有相关行:

$customers = Customer::find($clientId);
$customers->delete();
$customers->locations()->delete();
$customers->locations->objects()->delete();
$customers->locations->objects->subscriptions()->delete();
$customers->locations->objects->history()->delete();

并且还尝试了:

$customers = Customer::find($clientId);
$customers->delete();
$customers->locations()->delete();
$customers->locations()->objects()->delete();
$customers->locations()->objects()->subscriptions()->delete();
$customers->locations()->objects()->history()->delete();

Laravel删除客户和位置,但不删除对象,订阅和历史记录,并引发错误。

我也可以删除它们吗?

编辑:我改变了这样的顺序:

$customers = Customer::find($clientId);
$customers->locations()->objects()->subscriptions()->delete();
$customers->locations()->objects()->history()->delete();
$customers->locations()->objects()->delete();
$customers->locations()->delete();
$customers->delete();

并得到错误 Call to undefined method Illuminate\Database\Query\Builder::objects()

萨加尔·拉巴迪亚(Sagar Rabadiya)

您需要覆盖模型中的delete方法,以删除每个位置的所有相关对象,并且还应按顺序进行删除,因此,首先删除对象,然后是位置,然后是客户。对于前。

$customers = Customer::find($clientId);
$customers->locations()->delete();

现在在模型中为删除位置覆盖删除方法建模

class Location extends Model {
     public function delete() {
       $this->objects()->delete();
       parent::delete();
     }
}

//also delete hierarchy in your object model with overriding delete method

class Object extends Model {
     public function delete(){
        $this->history()->delete();
        $this->subscriptions()->delete();
        parent::delete();
     }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章