我有两张桌子。桌子reports
report_id | user_id | item_id
Run Code Online (Sandbox Code Playgroud)
和 reports_messages
report_id | user_id | item_id | messages
Run Code Online (Sandbox Code Playgroud)
我想,当我删除report_id的reports所有相关行,其匹配report_id在reports_messages被太删除。
在我的 ReportMessages 模型中,我有这种关系
public function reports(){
return $this->belongsTo('App\Report');
}
public function item(){
return $this->belongsTo('App\Item', 'item_id', 'id');
}
Run Code Online (Sandbox Code Playgroud)
在报表模型中
public function reportedItem(){
return $this->belongsTo('App\Item');
}
public function user(){
return $this->hasOne('App\User', 'id', 'user_id');
}
Run Code Online (Sandbox Code Playgroud)
到目前为止,我已经尝试过在 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');
Run Code Online (Sandbox Code Playgroud)
这仅在reports.. 中删除,不会删除数据透视表中的相关 report_id。}
Laravel具有的功能detach和attach处理数据透视表。所以你可以这样做来删除数据透视表中的记录:
ReportMessages::find(1)->reports()->detach($report_id);
Run Code Online (Sandbox Code Playgroud)
但是,这不会删除报告表中的行,因为它仍然可以链接到另一个对象。
更新:
所以,我刚刚注意到,您没有数据透视表,只有两个链接的模型。
您不必reports()在查询中加载关系以删除ReportMessages,您可以这样做:
Report::destroy($report_id);
ReportMessages::where('report_id',$report_id)->delete();
Run Code Online (Sandbox Code Playgroud)
这将删除报告和所有相应的报告消息。
| 归档时间: |
|
| 查看次数: |
7351 次 |
| 最近记录: |