gpt4 book ai didi

php - 如果最后一个 id 被删除,则获取下一个 id

转载 作者:行者123 更新时间:2023-11-29 15:18:04 25 4
gpt4 key购买 nike

我有 bill 和 Product_bill 表。

我需要在product_bill表中使用bill_id,并且我应该首先创建帐单,所以我做了这个

public function store(Request $request)
{

if( Bill::first() == null )
{
$bill_id = 1;
}
else {

$bill_id = Bill::orderBy('id','desc')->first()->id +1 ;
}
// dd($bill_id);
$brand_id = auth('brand')->id();
$bill = new Bill();
$bill->brand_id = $brand_id;
$bill->date = Carbon::today();

$data = $request->all();
$products = [];
$total = 0;
for($i = 0 ; $i<count($data['id']) ; $i++)
{
$prod = new ProductsBill();
$prod->product_id = $data['id'][$i] ;
$prod->quantity = $data['quantity'][$i];
$prod->bill_id = $bill_id;
$products[] = $prod->attributesToArray();
$price = Product::find($prod->product_id)->price;
$total += $price * $prod->quantity;
}
$bill->total = $total;
$bill->save();
ProductsBill::insert($products);

return redirect()->back();

}

当我删除任何账单时,product_bill 表中的新 bill_id 会获取最后一个账单的下一个数字,我需要知道接下来将创建 id谢谢。

最佳答案

如果您对 $bill 变量使用 save() 函数,您将通过访问 $bill->id 获取 id。如果您想确保交易完成,您可以使用DB transactions .

use DB;

class ... {

...

public function store(Request $request)
{
$brand_id = auth('brand')->id();
$bill = new Bill();
$bill->brand_id = $brand_id;
$bill->date = Carbon::today();

DB::beginTransaction();

try{
$bill->save();

$data = $request->all();
$products = [];
$total = 0;
for($i = 0 ; $i<count($data['id']) ; $i++)
{
$prod = new ProductsBill();
$prod->product_id = $data['id'][$i] ;
$prod->quantity = $data['quantity'][$i];
$prod->bill_id = $bill->id;
$products[] = $prod->attributesToArray();
$price = Product::find($prod->product_id)->price;
$total += $price * $prod->quantity;
}
$bill->total = $total;
$bill->save();
ProductsBill::insert($products);

DB::commit();

return redirect()->back();

} catch(\Illuminate\Database\QueryException $ex){
DB::rollBack();
// Exception redirect here

}
}

...

}

关于php - 如果最后一个 id 被删除,则获取下一个 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59545231/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com