首页 > 解决方案 > 如何将多张图片保存到 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)看到所有详细信息(包括图像)时,如何将它们提交到数据库?图像到图像表和产品详细信息到产品表。

标签: phpmysqllaravellaravel-5eloquent

解决方案


您应该使用 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();
} 

推荐阅读