我的产品总监。在这里,一个产品有很多图像。 Laravel在这里工作的一对多关系。当我创建新产品时,该产品有3,4张或许多张图片。产品图片表有两列,Product_id
和Image Name
。
$this->validate($request, [
'name'=>'required',
'model'=>'required',
'brand'=>'required|numeric',
'category'=>'required|numeric',
'subcategory'=>'required|numeric',
'quantity'=>'required|numeric',
'price'=>'required|numeric',
'description'=>'required',
'feature_image'=>'required|image|max:3000',
'product_images'=>'required|max:5000',
]);
$image = $request->file('feature_image');
$slug = Str::slug($request->name);
$currentDate = Carbon::now()->toDateString();
$tempName = $slug . '-' . $currentDate . '-' . uniqid() . '.' . $image->getClientOriginalExtension();
$path = 'backend/images/product/';
$imageName = $path . $tempName;
$image->move($path, $imageName);
$store_id = Store::where('user_id', Auth::id())->first();
$product_id = Product::latest()->first();
$product = new Product();
$product->user_id = Auth::id();
$product->store_id = $store_id->id;
$product->brand_id = $request->brand;
$product->category_id = $request->category;
$product->subcategory_id = $request->subcategory;
$product->name = $request->name;
$product->slug = $slug;
$product->model = $request->model;
$product->description = $request->description;
$product->quantity = $request->quantity;
$product->quantity = $request->quantity;
$product->price = $request->price;
$product->discount = $request->discount;
$product->feature_image = $imageName;
$product->pending = true;
$product->visible = true;
foreach ($request->product_images as $data){
$productImageTempName = $slug . '-' . $currentDate . '-' . uniqid() . '.' . $data->getClientOriginalExtension();
$productImageName = $path . $productImageTempName;
$data->move($path, $productImageName);
$product_image = new ProductImage();
$product_image->product_id = ????;
$product_image->image = $productImageName;
$product_image->save();
}
$product->save();
return redirect()->route('admin.product.index')->with('success', 'Product Successfully Create');
现在如何在问号的位置获得产品ID。我需要当前正在创建的产品ID。
答案 0 :(得分:0)
您应该在产品的图像之前保存产品,不仅要获得产品的ID,还要保存数据库的外键约束
而且您也应该在事务内进行以确保数据完整性
// .....
$product->visible = true;
DB::transaction(function ()use($product,$request,$slug,$currentDate,$path){
$product->save();
foreach ($request->product_images as $data){
$productImageTempName = $slug . '-' . $currentDate . '-' . uniqid() . '.' . $data->getClientOriginalExtension();
$productImageName = $path . $productImageTempName;
$data->move($path, $productImageName);
$product_image = new ProductImage();
$product_image->product_id = $product->id;
$product_image->image = $productImageName;
$product_image->save();
}