我有一个产品表,其中有一列名称图像,在将它们上传到服务器后,我将所有图像的名称存储在其中。
但我的问题是,当我想更新任何产品并且想向图像列添加更多图片时,我收到此错误
Array to string conversion (SQL: update `products` set `pro_name` = Test, `images` = A6FC3-091547-2Nx.jpg, `updated_at` = 2018-06-17 03:29:20 where `id` = 1)
这是我的代码:
public function update(Request $request, $id){
$images=array();
if($files=$request->file('images')){
foreach($files as $file){
$extension = $file->getClientOriginalExtension();
$fileName = str_random(5)."-".date('his')."-".str_random(3).".".$extension;
$upfolder = "admin/UploadImages"."/";
$file->move($upfolder , $fileName);
$images[]=$fileName;
}
}
$pros = Product::find($id);
$pros->pro_name = $request->input('pro_name');
$pros->pro_code = $request->input('pro_code');
$pros->aval = $request->input('aval');
$pros->price = $request->input('price');
$pros->colors = $request->input('colors');
$pros->images = array_merge(explode(",",$pros->images), $images);
$pros->cat_id = $request->input('cat_id');
$pros->hide = $request->input('hide');
$pros->save();
return redirect('products');
}
提前致谢
就像其他人所说的那样,您正在尝试将数组存储为字符串。 使用 php 的 implode() 函数是您需要寻找的地方。
您还可以查看我之前提到的演员表。
替代方法
我不知道你为什么要让自己变得如此复杂。可能有一个非常明显的原因,但我看不到。
为什么不使用数据透视表product_product_image创建另一个模型ProductImage,这样您就可以简单地在两者上定义属于多个关系
产品
public function images()
{
return $this->belongsToMany(ProductImage::class);
}
产品图片
public function products()
{
return $this->belongsToMany(Product::class);
}
创建产品时就这样
你可以这样做:
$product = Product::create([
//create your product here.
]);
foreach($request->images[] as $image){
$product->images()->attach();
}
然后,当您更新图像时,您可以将它们全部显示在页面中,也许一个ajax调用可以在单击时简单地删除图像。简单地说:
$product = Product::find($request->product_id);
$image = ProductImage::find($request->image_id);
$product->images()->detach($image);
这意味着在将整个产品更新发布回服务器之前,您想要删除的任何内容都已经完成。
现在,您可以使用我为您的创建方法发布的相同功能将任何新图像添加到您的产品中。
同样,您这样做可能是有原因的,但我只是向您展示另一种利用 laravel 功能的方法。
你需要使用这个方法:
array_push($arrayName, Item1, [Item2, Item3]);
我想你已经在第10行使用了,
$images[]=$fileName;
,LHS是一个数组,RHS是字符串值。请使用 array_push($images, $fileName);
来代替。
简而言之,我的意思是:
将您的
$images[]=$fileName;
替换为 array_push($images, $fileName);
。
在这一行中:
$pros->images = array_merge(explode(",", $pros->images), $images);
array_merge()
返回一个数组。当您保存记录时,它会尝试将该数组转换为字符串,从而给出您所看到的错误。
根据您当前的逻辑,您需要在合并后内爆数组:
$pros->images = implode(",", array_merge(explode(",",$pros->images), $images));
现在字符串将成功保存到数据库中。
另一个特定于 Laravel 的选项是将
images
字段添加到 $casts
模型上的 Product
数组中。
protected $casts = [
'images' => 'array',
];
现在,数据将作为字符串存储在数据库中,但每当您访问它时,Laravel 都会自动将其转换为数组。
如果您按照上面的方式更新了
$casts
属性,您的代码将只是:
$pros->images = array_merge($pros->images, $images);
如果数据库中有现有数据,则无法简单地进行此更改,因为 Laravel 将数组存储为 json,而不仅仅是逗号分隔的列表,并且现有数据将不兼容。但是,如果这是新的开发,我建议从这种方法开始。