亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如果最后一個被刪除,則獲取下一個 id

如果最后一個被刪除,則獲取下一個 id

PHP
肥皂起泡泡 2022-07-09 10:04:15
我有 bill 和 product_bill 表。我需要在 product_bill 表中使用 bill_id 并且我應該首先創建賬單,所以 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,謝謝。
查看完整描述

2 回答

?
繁星coding

TA貢獻1797條經驗 獲得超4個贊

如果您在變量save()上使用函數$bill,您將通過訪問$bill->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


        }

    }


    ...


}


查看完整回答
反對 回復 2022-07-09
?
慕運維8079593

TA貢獻1876條經驗 獲得超5個贊

如果我正確理解您的問題,您可能可以使用 mysql 函數來獲取最后插入的 ID 并添加一個。

https://dev.mysql.com/doc/refman/8.0/en/information-functions.html#function_last-insert-id


查看完整回答
反對 回復 2022-07-09
  • 2 回答
  • 0 關注
  • 116 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號