2 回答
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
}
}
...
}
TA贡献1876条经验 获得超5个赞
如果我正确理解您的问题,您可能可以使用 mysql 函数来获取最后插入的 ID 并添加一个。
https://dev.mysql.com/doc/refman/8.0/en/information-functions.html#function_last-insert-id
- 2 回答
- 0 关注
- 86 浏览
添加回答
举报