Laravel 5.4 - 从数据透视表中删除特定记录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45908315/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 16:33:40  来源:igfitidea点击:

Laravel 5.4 - Deleting specific records from the pivot table

phplaravelmany-to-manysql-delete

提问by Sérgio Nader

For each visit I may have many products; therefore the pivot table (product_visit) has the fields: id, product_id, visit_id, qtd and amount.

每次访问我可能有很多产品;因此数据透视表 (product_visit) 具有字段:id、product_id、visit_id、qtd 和 amount。

To delete a visit and its related records on the pivot table, everything works fine:

要删除数据透视表上的访问及其相关记录,一切正常:

 public function getVisitDelete($id){
    $visits = Visit::find($id);
    $visits->products()->detach();
    $visits->delete();
}

However, I could not figure out how to delete one specific record from the pivot table using detach or something similar. So I ended up doing the following:

但是,我无法弄清楚如何使用 detach 或类似方法从数据透视表中删除一条特定记录。所以我最终做了以下事情:

public function getProductVisitDelete(){
    $visit_id   =   (int)Request('visit_id');
    $product_id =   (int)Request('product_id');
    $sqlDelete = "delete from product_visit where visit_id=$visit_id and product_id = $product_id";
    DB::select($sqlDelete);
}

Though it works, I am far being happy with this solution -- looks like I am missing something.

虽然它有效,但我对这个解决方案很满意——看起来我遗漏了一些东西。

回答by jaysingkar

You can use wherePivot()method to detach specific product from the visit.

您可以使用wherePivot()方法从访问中分离特定产品。

$visits = Visit::find($visit_id);
$visits->products()->wherePivot('product_id','=',$product_id)->detach();

UpdateAs given in Laravel docs"Attaching / Detaching" section, you can pass the related model's id that you want to remove in detach()method. Example

更新Laravel 文档“附加/分离”部分中所述,您可以在detach()方法中传递要删除的相关模型的 id 。例子

$visits = Visit::find($id);
$visits->products()->detach($product_id);