2017-01-26 9 views
0

私は2つのテーブルを持っています。表reportsLaravelのピボットテーブルの行を削除

report_id | user_id | item_id 

reports_messages

report_id | user_id | item_id | messages 

私はreport_idreports上のすべての関連する行を削除する場合も削除されるようにreports_messagesreport_idをマッチングされたいです。

私はこれまでのところ、私はSO

public function destroy($report_id){ 

    Report::destroy($report_id); 
    ReportMessages::find(1)->reports()->where('report_id',$report_id)->delete(); 

    return redirect()->route('user.ports'); 

この削除にここに設立されたこのソリューションを試してみた。この関係

public function reports(){ 
    return $this->belongsTo('App\Report'); 
} 

public function item(){ 
    return $this->belongsTo('App\Item', 'item_id', 'id'); 
} 
レポートモデルで

public function reportedItem(){ 

    return $this->belongsTo('App\Item'); 
} 

public function user(){ 
    return $this->hasOne('App\User', 'id', 'user_id'); 
} 

を持っている私のReportMessagesモデルで

reportsのみ。ピボットテーブル内の関連するreport_idは削除されません。

}

答えて

2

Laravelは、ピボットテーブルに対処する機能detach and attachを有しています。 ですから、ピボットテーブル内のレコードを削除するには、この操作を行うことができます。それはまだ別のオブジェクトにリンクされている可能性があるため

ReportMessages::find(1)->reports()->detach($report_id); 

しかし、これは、レポートのテーブルの行を削除しません。

更新:
だから、私は気づいた、あなたはあなただけリンクされている2つのモデルがあり、ピボットテーブルを持っていません。あなたはReportMessagesを削除するクエリでreports()関係をロードする必要はありません

、あなたはちょうどこのようにそれを行うことができます。

Report::destroy($report_id); 
ReportMessages::where('report_id',$report_id)->delete(); 

これは、レポートを削除し、対応するすべてのreportmessagesます。

+0

ありがとうございました。私はこのエラーを持っています。定義されていないメソッドを呼び出す\データベース\クエリ\ビルダー::デタッチ() ' – user5996816

+0

私は自分の答えを更新しましたが、実際にはピボットテーブルはありません... – Jerodev

+0

ああ、神。そして私はピボットテーブルでそれをやろうとしていました。それらは実際にはモデルによってのみリンクされています。愚かな私。助けてくれてありがとう! – user5996816

関連する問題