我有一个表单正在提交,以添加项目到数据库中。这些物品是为来自不同公司的不同人准备的。当有人提交表格时,我会得到为该公司输入的最后一个数字,然后将其递增1。因此,如果你来自PPT,我会检查为PPT输入的最后一个数字,然后添加1并更新数据库。问题是,如果5个人同时按下submit,那么所有人都会生成相同的数字。
我不能使用ID的内建增量功能,因为不同的公司在同一个表上,所以PPT可能现在添加一个项目,然后另一个公司(TTS)添加10个项目。当我在10个TTS之后添加下一个PPT时,我将获得添加的最后一个PPT项,并递增1。
我如何在laravel中修复这个问题,即使每个人都同时点击submit,也总是得到一个新的数字。
请参阅下面的插入代码:
$courier = $cour->where('company_name', $request->idlm)->first();
$latest = $newInvent->where('idlm', $request->idlm)
->orderBy('id', 'desc')
->latest()->first();
if ($latest == null) {
$updatebl = 10000;
} else {
$updatebl = intval($latest->house_number) + 1;
}
$newInvent->tracking_number = $request->test_num;
$newInvent->first_name = $request->first_name;
$newInvent->last_name = $request->last_name;
$newInvent->description = $request->description;
$newInvent->houseBTL_number = strval($updatebl);
$newInvent->save();发布于 2018-07-24 07:13:19
我认为你已经把它整理好了,但可以考虑这样做:
首先创建并保存你的$newInvent,但不要带上你的号码。
接下来,运行一个查询来计算ID较小的公司的项目数,并将其用作数字。
// create and save the new inventory item
$newInvent = new ...
$newInvent->first_name = ...
...
$newInvent->save();
// calculate the sequence ID for the item
$seqId = InventoryItem::where('company_name', 'Acme Inc')->where('id', '<', $newInvent->id)->count();
$newInvent->number = $seqId;
$newInvent->save();因为您使用的是SQL自动增量ID(保证惟一),所以可以确保并发问题得到解决。
如果要从InventoryItem表中删除项目,请确定您正在使用Eloquent's soft deletes,然后将计数查询更改为:
$seqId = InventoryItem::where('company_name', 'Acme Inc')->where('id', '<', $newInvent->id)->withTrashed()->count();来计算已删除项目的数量。
https://stackoverflow.com/questions/51487948
复制相似问题