Php 删除Laravel中透视表中的行

Php 删除Laravel中透视表中的行,php,laravel,laravel-5,Php,Laravel,Laravel 5,我有两张桌子。表格报告 和报告信息 我想在删除报表上的报表id时,也删除与报表消息中的报表id匹配的所有相关行 在我的ReportMessages模型中,我有这个关系 public function reports(){ return $this->belongsTo('App\Report'); } public function item(){ return $this->belongsTo('App\Item', 'item_id', 'id'); }

我有两张桌子。表格报告

和报告信息

我想在删除报表上的报表id时,也删除与报表消息中的报表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');
}
到目前为止,我已经尝试了这个解决方案

public function destroy($report_id){

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

    return redirect()->route('user.ports');
这仅在报告中删除。。不删除透视表中的相关报表id。 }Laravel具有处理数据透视表的功能。 因此,您可以执行以下操作以删除数据透视表中的记录:

ReportMessages::find(1)->reports()->detach($report_id);
但是,这不会删除reports表中的行,因为它仍然可以链接到另一个对象

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

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

Report::destroy($report_id);
ReportMessages::where('report_id',$report_id)->delete();
这将删除报表以及所有相应的报表消息。

Laravel具有处理透视表的功能。 因此,您可以执行以下操作以删除数据透视表中的记录:

ReportMessages::find(1)->reports()->detach($report_id);
但是,这不会删除reports表中的行,因为它仍然可以链接到另一个对象

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

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

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

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

我知道我迟到了,但对于这种关系,最好是在表报告中为特定链接表定义外键\u消息,如下所示

> $table->integer'report\u id'->无符号->索引; $table->foreign'report_id'->references'id'->on'reports'->onDelete'cascade'; $table->integer'message_id'->无符号->索引; $table->foreign'message_id'->references'id'->on'messages'->onDelete'cascade'

当您执行类似操作时,只要从数据库中删除消息或报表而不需要分离方法,透视表数据就会被删除。
如果消息或报告与其他数据有关系,那么最好的选择是,当数据被删除时,消息应该被自动删除,在这种情况下,我们不必担心再次分离数据,最好在表报告中定义特定链接表的外键\u消息,如下所示

> $table->integer'report\u id'->无符号->索引; $table->foreign'report_id'->references'id'->on'reports'->onDelete'cascade'; $table->integer'message_id'->无符号->索引; $table->foreign'message_id'->references'id'->on'messages'->onDelete'cascade'

当您执行类似操作时,只要从数据库中删除消息或报表而不需要分离方法,透视表数据就会被删除。
如果消息或报告与其他数据有关系,最好的选择是,当数据被删除时,消息应该自动删除,在这种情况下,我们不必担心再次分离数据

谢谢。我对undefined方法Illumb\Database\Query\Builder::detachOh,天哪,有个错误调用。我试着用透视表来做。它们实际上只由模型链接。我真傻。谢谢你的帮助!多谢。如果关系还可以的话,一切都会好起来的。谢谢。我对undefined方法Illumb\Database\Query\Builder::detachOh,天哪,有个错误调用。我试着用透视表来做。它们实际上只由模型链接。我真傻。谢谢你的帮助!多谢。如果关系正常,一切都会好起来的。