table checkbox in laravel delete multiple data with foreign key error

table checkbox in laravel delete multiple data with foreign key error

我有一个产品复选框列表,我想使用复选框删除所有数据以及其他 table 中的外键。

这是我所得到的,从我的 table 我创建了一个表单,该表单被路由以删除从复选框中选中的数据。

<form action="{{ route('admin.delproducts') }}" method="get" id="delprod">
    {{ csrf_field() }}

    <table class="table table-hover">                                    
        <thead>                        
            <tr>
              <th width="4%"></th>
              <th width="17%">SUB-CATEGORY</th>
              <th width="30%">PRODUCT NAME</th>
              <th width="10%">QTY</th>
              <th width="10%">STATUS</th>
              <th width="25%">UPDATED</th>                
            </tr>
        </thead>
        <tbody>
             @foreach($products as $key => $data)
            <tr>
                <td><input type="checkbox" name="products[]" value="{{ $data->product_id }}" />&nbsp;</td>                            
                <td><a href="#"> {{ $data->name }} </a></td>
                <td><a href="#"> {{ $data->product_name }} </a></td>
                <td><a href="#"> {{ $data->quantity }} </a></td>
                <td><a href="#"> {{ $data->status }} </a></td>
                <td>{{ $data->updated_at }}</td>                            
            </tr>
            @endforeach
        </tbody>
    </table>
    </form>
<p data-placement="top" data-toggle="tooltip" title="Delete"><button class="btn btn-danger btn-sm pull-right delbtn" data-title="Delete" data-toggle="modal" data-target="#delete" ><span class="glyphicon glyphicon-trash"></span></button></p>

我在表单外创建了我的按钮,但我已经为它创建了一个 javascript。

$(".delbtn").click( function() {
    $('#delprod').submit();
});

在我的控制器中,这是我所做的:

public function deleteProducts(Request $request) {

    Product::destroy($request->products);

    return redirect()->route('admin.product');
}

我得到了一个错误,因为这个产品 table 有一个来自 table 的外键 Product_image 我怎样才能让控制器删除我的 Product_image 中的所有数据table 有 product_id 正在复选框中选中?

我试着制作了一个模型 Product_image 并在我的控制器中尝试了这个

Product_image::destroy($request->products); 

但它给我错误,因为它说它不存在。在进行查询以删除复选框传递的外键时有什么建议吗? .类似于从复选框中删除接受数组的查询。?

如果您在产品图片之间有关系,您可以这样做。 (我假设你的关系名称是 productImage。Laravel destroy 函数不会删除关系。如果你没有定义 onDelete('cascade')

如果你想删除关系,你需要在迁移文件或直接在数据库中定义 onDelete。

  $table
    ->foreign('product_id')
    ->references('id')
    ->on('product_image')
    ->onDelete('cascade');

在那之后你可以尝试使用 destroy(不确定它是否会删除关系)如果不是那么你可以这样做

public function deleteProducts(Request $request) {
    foreach ($request->products as $product_id) {
        $product = Product::find($id);
        $product->productImage()->delete();
    }

    return redirect()->route('admin.product');
}

如果没有关系,则需要手动删除关系数据。