如何从 Vue 对 Laravel 执行批量删除?



我正在尝试为网站制作一个大规模的删除功能,以同时删除产品列表。我通过 excel 插入数据。

控制器功能

public function destroy(Request $request)
{
ini_set('max_execution_time', 300);
$products = $request->all();
try {
DB::beginTransaction();
foreach ($products as $product) {
$dbProduct = $this->getProduct($product['SKU']);
Log::error($dbProduct);
$dbProduct->delete();
}
DB::commit();
} catch (Exception $e) {
DB::rollBack();
throw new HttpException(500, 'Sucedio un error eliminando la información favor intentar de nuevo');
}
}
private function getProduct($sku)
{
$product = Product::where('sku', $sku)->first();
return $product;
}

我不确定如何在 vue 部分执行@click方法,现在我有这个,但这用于上传到其他页面,不确定要更改什么以使其删除。它接收一个数组,该数组已分成 50 个组,即(数据、索引(。

sendData(data, index) {
this.loading = true;
this.error = {};
this.$http.post(this.baseUrl, data, this.params).then(
() => {
this.successAction();
this.statuses[index] = 1;
this.errorDis = false;
},
res => {
this.showErrors(res);
this.statuses[index] = 2;
this.errorDis = true;
}
);
}

目前我得到了成功状态,但它没有删除产品

恕我直言,您可以使用一个查询而不是$products->count() * 2查询删除所有产品,如下所示:

public function destroy(Request $request)
{
//ini_set('max_execution_time', 300); no need IMHO
$products = collect($request->all());
$skus = $products->pluck('SKU');
try {
DB::beginTransaction();
Product::whereIn('sku', $skus)->delete();
DB::commit();
} catch (Exception $e) {
DB::rollBack();
throw new HttpException(500, 'Sucedio un error eliminando la información favor intentar de nuevo');
}
// it's better to return something here
return response('Finished!', 200);
}

更新:正如@ceejayoz所指出的,上面的函数绕过了各个雄辩的事件deletingdeleted,如果您需要它们,或者您需要单Product模型,这里有一个不太精简的版本,可以执行$products->count() + 1查询:

public function destroy(Request $request)
{
//ini_set('max_execution_time', 300); probably unneeded
$skus = collect( $request->all() )->pluck('SKU');
$products = Product::whereIn('sku', $skus)->get();
try {
DB::beginTransaction();
foreach ($products as $product) {
Log::error($product);
$product->delete();
}
DB::commit();
} catch (Exception $e) {
DB::rollBack();
throw new HttpException(500, 'Sucedio un error eliminando la información favor intentar de nuevo');
}
// it's better to return something here
return response('Finished!', 200);
}

最新更新