使用laravel删除相关行

时间:2016-09-24 08:31:05

标签: laravel laravel-5

我试图删除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()

3 个答案:

答案 0 :(得分:1)

您需要覆盖模型中的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();
     }
}

答案 1 :(得分:0)

最有可能以相反的顺序进行 如果您删除了"父母","孩子",他找不到。
试试这个。

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

答案 2 :(得分:0)

当你说

$customers->locations()->delete()

您正试图删除Collection。您应该删除Model

所以使用

获取所有位置

$locations = $customer->locations

然后使用foreach循环删除每个location

foreach($locations as $location) {
  $location->delete();
}

同样删除所有其他相关模型。