dongou1970 2017-01-26 15:06
浏览 100
已采纳

删除Laravel中数据透视表中的行

I have two tables. Table reports

report_id | user_id | item_id

and reports_messages

report_id | user_id | item_id | messages

I want when I delete report_id on reports all related rows which matching report_id in reports_messages to be deleted too.

In my ReportMessages Model I have this relation

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

public function item(){
    return $this->belongsTo('App\Item', 'item_id', 'id');
}   

In Report model

public function reportedItem(){

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

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

So far I've tried this solution founded here on 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');

This deletes only in reports.. doesn't delete related report_id's in pivot table. }

  • 写回答

2条回答 默认 最新

  • duansaxf095988 2017-01-26 15:08
    关注

    Laravel has the functions detach and attach to deal with pivot tables. So you can do this to remove the record in the pivot table:

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

    This will however not remove the row in the reports table because it could still be linked to another object.

    Update:
    So, I just noticed, you don't have pivot tables, you only have two models that are linked.

    You don't have to load the reports() relation in your query to remove the ReportMessages, you can just do it like this:

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

    This will remove the report, and all corresponding reportmessages.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)