gpt4 book ai didi

php - 在 Laravel 中删除数据透视表中的行

转载 作者:行者123 更新时间:2023-12-05 08:33:20 24 4
gpt4 key购买 nike

我有两张 table 。表报告

report_id | user_id | item_id

reports_messages

report_id | user_id | item_id | messages

当我删除 reports 上的 report_id 时,我希望删除所有与 reports_messages 中的 report_id 匹配的相关行也是。

在我的 ReportMessages 模型中我有这种关系

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');
}

到目前为止,我已经尝试过这个基于 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');

这仅在 reports 中删除。不会删除数据透视表中的相关 report_id。

最佳答案

Laravel 具有函数 detach and attach处理数据透视表。所以你可以这样做来删除数据透视表中的记录:

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

但这不会删除报告表中的行,因为它仍然可以链接到另一个对象。

更新:
所以,我刚刚注意到,您没有数据透视表,您只有两个链接的模型。

您不必在查询中加载reports() 关系来删除ReportMessages,您可以这样做:

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

这将删除报告以及所有相应的报告消息。

关于php - 在 Laravel 中删除数据透视表中的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41876492/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com