2016-09-24 2 views
-1

に関連する行を削除:私はLaravelに関連するすべての行を削除しようとしています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()

+0

関連するモデルを削除してから親モデルを削除しようとしましたか? – Anik

+0

@Anik私はソフト削除を使用していますが、それは問題ではありません – AgeDeO

+0

それはどんなエラーを投げましたか? – SteD

答えて

1

あなたは場所や、顧客、その後、順番にする必要がありますそれぞれの場所 のために、関連するすべてのオブジェクトを削除しても削除するには、モデル内の削除メソッドをオーバーライドする必要があるので、最初のオブジェクトを削除します。例えば、

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

今位置削除オーバーライドのためにあなたはCollectionを削除しようとしている

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

情報を追加するだけで、親モデルが削除されるたびにすべての関連モデルを削除したい場合にのみ有効です。 – Anik

+0

それがケースでない場合、例えばdeleteReferences()のようなカスタム名でメソッド名を変更するので、デフォルトのalways deleteメソッドとして動作しません。 –

0

ほとんどのエラーを取得します。
"親"、つまり "子供"を削除した場合、彼は見つけられません。
これを試してください。

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

好きでモデル何かをする方法を削除します。 Modelを削除する必要があります。

ので

$locations = $customer->locations

を使用して、すべての場所を取得し、各locationを削除するforeachループを使用します。

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

他の関連モデルも同様に削除してください。

関連する問題