简体   繁体   中英

Deleting Row in Pivot table by id

This is how the structure of my pivot table looks like

category_product

id

category_id --FK

product_id --FK

Now i my pivot i have data like

category_product

id    category_id    product_id
1        1             4
2        1             16

Now in my table, I am able to display all items for category 1 which has product 4 and 16 . I want to delete a row 1 using the id but I can't get that working with my code.

Code

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>

You have to use detach method in order to delete rows from the pivot table

For example to detach product 4 from category 1:

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

To detach a list of products for example 4 and 16 from category 1:

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

The detach method can accept an array of ids

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM