按ID删除数据透视表中的行

时间:2017-11-12 11:48:17

标签: php laravel

这就是我的数据透视表的结构如何

category_product

id

category_id --FK

product_id --FK

现在我的支点我有像

这样的数据

category_product

id    category_id    product_id
1        1             4
2        1             16

现在,在我的表格中,我可以显示category 1的所有项目product 4 and 16。我想使用row 1删除id,但我无法使用我的代码。

代码

public function delete($id)
{
    DB::table("category_product")->whereIn('id', $id)->delete();      
}

HTML

<table class="table"> 
    <thead>
        <tr> 
            <th>Category No#</th>
            <th>Action</th>
        </tr>                
    </thead>
    <tbody>
        @foreach($categories as $cat)
            <tr>
                <td>{{$cat->id }}</td>
                    <a href="{!! action('Controller@delete', 1) !!}">
                        <i class="fa fa-trash" style="font-size:20px"></i>
                    </a>
                </td>
            </tr>
        @endforeach
    </tbody>
</table>

1 个答案:

答案 0 :(得分:0)

您必须使用detach method才能从数据透视表中删除行

例如,将产品4从类别1中分离出来:

$category = App\Category::find(1);
$category->products()->detach(4);

从类别1中分离示例4和16的产品列表:

$category = App\Category::find(1);
$category->products()->detach([4, 16]);

detach方法可以接受一组id

相关问题