【问题标题】:How to save multiple images to the database in Laravel?如何将多张图片保存到 Laravel 的数据库中?
【发布时间】:2019-06-30 19:35:03
【问题描述】:

我正在尝试在数据库中保存多个产品图像。我创建了 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) 时,我看到了所有的细节,包括图像,但是我如何将它们提交到数据库?图片到图片表和产品详细信息到产品表。

【问题讨论】:

  • 您在过去一两天中已经就此提出了七个问题,但您并没有真正从给出的答案中提取信息。我可以建议您稍微备份一下,并尝试一些教程来帮助您了解我认为您可能缺少的一些基础知识。尝试 Laracasts 作为初学者,Jeff Way 非常棒。不努力,但我认为如果没有一些基础知识,SO 将无法帮助您构建所需的东西:)
  • 没有不好的感觉。我尝试按照您建议的方式进行操作,但无法获取产品 ID。 @Watercayman
  • 如果您真的想将图像存储在数据库中(通常最好使用文件系统),请使用file_get_contents()

标签: php mysql laravel laravel-5 eloquent


【解决方案1】:

您应该使用 Image::create() 在 images 表中插入图像,并且在 images 表中您应该为产品的 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();
} 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-17
    • 1970-01-01
    • 2021-03-30
    • 1970-01-01
    • 1970-01-01
    • 2015-04-20
    • 2015-04-14
    • 1970-01-01
    相关资源
    最近更新 更多