php - 如何将多张图片保存到 Laravel 的数据库中?
问题描述
我正在尝试在数据库中保存多个产品图像。我创建了 images 表并与 products 表建立了关系。
控制器
public function store(Request $request)
{
$formInput = $request->all();
$image = array();
if ($files = $request->file('image')) {
foreach ($files as $file) {
$name = $file->getClientOriginalName();
$file->move('images', $name);
$image[] = $name;
}
}
//dd($formInput);
Product::create(array_merge($formInput,
[
// 'product_id'=>$product->id,
'image' => 'what to put here',
'seller_id' => Auth::user()->id,
]));
return redirect()->back();
}
图像模型
class Image extends Model
{
protected $table = 'images';
protected $fillable = ['product_id', 'image'];
public function product()
{
return $this->belongsTo('App\Product', 'product_id');
}
}
产品型号
class product extends Model
{
protected $table = 'products';
protected $primaryKey = 'id';
protected $fillable = ['seller_id', 'pro_name', 'pro_price', 'pro_info', 'stock', 'category_id'];
public function images()
{
return $this->hasMany('App\Image', 'product_id');
}
}
当我dd($formInput)
看到所有详细信息(包括图像)时,如何将它们提交到数据库?图像到图像表和产品详细信息到产品表。
解决方案
您应该使用 Image::create() 在图像表中插入图像,并且在图像表中您应该为产品 ID 创建一个外键(product_id)。Products 表中将没有关于图像的条目。只需创建具有正常字段的产品,不包括任何图像细节。
public function store(Request $request)
{
$formInput = $request->all();
$image = array();
if ($files = $request->file('image')) {
foreach ($files as $file) {
$name = $file->getClientOriginalName();
$file->move('images', $name);
$image[] = $name;
}
}
//dd($formInput);
Image::createMany([
'product_id': //'value of id': Same for all images of this product
],[...])
Product::create(array_merge($formInput,
[
// 'product_id'=>$product->id,
// 'image' => 'what to put here',
'seller_id' => Auth::user()->id,
//Other Fields' details...
]));
return redirect()->back();
}
推荐阅读
- ios - CGImageDestinationFinalize 失败,有时会崩溃
- angular - nativescript errorPubNub 调用失败,查看状态了解详情
- hibernate - JPA 实体将 SQL 函数结果映射到瞬态字段
- dart - 将 json 转换为 Map
> 格式 - python - 在python中比较单个元素和数组时选择最大值
- python - 列表中的重复项 - 在第二项之后插入输出
- c# - API 返回图片
- hyperledger-fabric - Hyperledger 结构加入通道:错误:2 未知:访问被拒绝:通道 [] 创建者组织 [Org1MSP]
- php - 尝试使用作曲家安装 guzzle 时如何解决错误?
- jenkins - 启用“块构建直到完成”选项触发远程作业时,Jenkins Pipeline 失败