我正在使用Laravel框架,但是这个答案应该能够在没有框架知识的情况下得到解答。
我有一个名为images的数据库表。对于我的网站,每个视频都有一个主视频图像,一个较小的特征图像,一个风景和肖像图像,gallery_six(这是一张有6张图片的图片)。每个其他图像都被归类为normal_image。
表格如下:
array(
[video_image_link] => 'link'
[video_image_alt] => 'alt'
[feature_image_link] => 'link'
[feature_image_alt] => 'alt'
[gallery_landscape_image_link] => 'link'
[gallery_landscape_image_alt] => 'alt'
[gallery_portrait_image_link] => 'link'
[gallery_portrait_image_alt] => 'alt'
)
现在,当我创建图库时,我试图将记录插入到数据库中,但我的代码看起来很乱,我不确定如何重构它。
当我的帖子请求进入控制器时,它看起来像这样:
public static function uploadMainImages($request,$gallery_id)
{
//upload video image
Image::create([
'gallery_id'=>$gallery_id,
'link'=>$request['video_image_link'],
'alt'=>$request['video_image_alt'],
'video_image'=>1,
'feature_image'=>0,
'gallery_landscape'=>0,
'gallery_portrait'=>0,
'gallery_six'=>0,
'normal_image'=>0,
]);
//upload feature image
Image::create([
'gallery_id'=>$gallery_id,
'link'=>$request['feature_image_link'],
'alt'=>$request['feature_image_alt'],
'video_image'=>0,
'feature_image'=>1,
'gallery_landscape'=>0,
'gallery_portrait'=>0,
'gallery_six'=>0,
'normal_image'=>0,
]);
在我的方法中,我这样做:
fetchQuery
等等......
有没有更好的方法让我这样做,而不更改数据库,只使用当前形式的帖子数据?
答案 0 :(得分:-2)
public static function uploadMainImages($request,$gallery_id) {
createImg($gallery_id, $request['video_image_link'], $request['video_image_alt'], "video_image");
createImg($gallery_id, $request['feature_image_link'], $request['feature_image_alt'], "feature_image");
createImg($gallery_id, $request['gallery_landscape_image_link'], $request['gallery_landscape_image_alt'], "gallery_landscape");
createImg($gallery_id, $request['gallery_portrait_image_link'], $request['gallery_portrait_image_alt'], "gallery_portrait");
}
function createImg($id, $link, $alt, $type) {
$video_image = ($type == "video_image" ? 1 : 0);
$feature_image = ($type == "feature_image" ? 1 : 0);
$gallery_landscape = ($type == "gallery_landscape" ? 1 : 0);
$gallery_portrait = ($type == "gallery_portrait" ? 1 : 0);
$gallery_six = ($type == "gallery_six" ? 1 : 0);
$normal_image = ($type == "normal_image" ? 1 : 0);
Image::create([
'gallery_id'=>$id,
'link'=>$link,
'alt'=>$alt,
'video_image'=> $video_image,
'feature_image'=> $feature_image,
'gallery_landscape'=> $gallery_landscape,
'gallery_portrait'=> $gallery_portrait,
'gallery_six'=> $gallery_six,
'normal_image'=> $normal_image,
]);
}
也许是这样的。使用此功能可以创建所需的图像类型。