我正在尝试为我的产品图片制作特色照片。我已经成功制作了带有与其关联的产品图片ID的单选按钮。当我单击单选按钮并将其提交时,它会将product_images表中的“功能”列设置为1(或True)。我遇到的问题是,我只希望每个产品都带有一张照片。当我选择并单击要显示的其他图像时,它也会以1插入数据库。
我该怎么做,所以每个产品只有1张特色图片。因此,如果选择了其他图像,请使用该product_id将所有其他图像默认恢复为0(或False)。
这是我的表格:
<form method="post" action="/store/admin/products/add/featured/{{ $products->id }}">
{!! csrf_field() !!}
@foreach($products->photos as $set)
<label>{{ $set->id }} </label>
<input type="radio" name="featured" value="{{ $set->id }}" {{ $set->featured === 1 ? "checked=checked" : "" }}>
@endforeach
<button type="submit" class="btn btn-primary waves-effect waves-light">Feature Image</button>
</form>
我在DB中插入特色图片的功能:
public function storeFeaturedPhoto($id, Request $request) {
// Check if radio button is checked or not for featured image
$featured = Input::has('featured') ? true : false;
// Validate featured button
$this->validate($request, [
'featured' => 'required'
]);
// Grab the ID of the Image being featured from radio button
$featured2 = Input::get('featured');
// Select All from product_images where the photo ID is the photo id being selected from radio button
$image = ProductPhoto::where('id', '=', $featured2);
// Select from product_images wherew featured = 1 and the product ID = to the product id in the URL, then count the results
$count = ProductPhoto::where('featured', '=', 1)->where('product_id', '=', $id)->count();
if ($count > 1) {
// Do something here to deselect all other images with this product_id??????????
}
// update the product_photos table with the featured photo
$image->update([
'featured' => $featured,
]);
// Return redirect back
return redirect()->back();
}
我的product_images表:
和我的形式:
最佳答案
这应该可以工作,只需在ProductPhoto Model中添加一些行即可。
class ProductPhoto extends Model
{
protected $fillable = ['featured'];
//other things...
}
控制器:
public function storeFeaturedPhoto($id, Request $request) {
// Validate featured button
$this->validate($request, [
'featured' => 'required|exists:product_images,id'
]);
// Grab the ID of the Image being featured from radio button
$featured = Input::get('featured');
// Some mass updates
ProductPhoto::where('product_id', '=', $id)->update(['featured' => 0]);
ProductPhoto::findOrFail($featured)->update(['featured' => 1]);
// Return redirect back
return redirect()->back();
}