Laravel 如何最好地将产品id链接到图像,以便一个产品可以链接多个图像

Laravel 如何最好地将产品id链接到图像,以便一个产品可以链接多个图像,laravel,Laravel,我在电子商务网站上工作。我有产品,我上传与1显示图像罚款。我希望将多个图像分别上传到不同的表中,但按产品id链接,以识别属于此产品的图像 这是我的数据库模式 Schema::create('product_images', function (Blueprint $table) { $table->increments('id'); $table->integer('product_id'); $table->string

我在电子商务网站上工作。我有产品,我上传与1显示图像罚款。我希望将多个图像分别上传到不同的表中,但按产品id链接,以识别属于此产品的图像

这是我的数据库模式

    Schema::create('product_images', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('product_id');
        $table->string('name');
        $table->string('size');
        $table->timestamps();

        $table->foreign('product_id')
              ->references('id')->on('products')
              ->onDelete('cascade');
    });

使用此功能,我可以很好地上传图像,但当我检查数据库时,如果您使用的是laravel Elequent,则在上传这些图像时,没有外键链接到捕获的产品。使用一对多关系。一对多关系定义为单个模型拥有多个模型

否则,您可以使用laravel查询生成器连接这两个表


您需要在产品上定义一对多关系

这里有一个例子

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    /**
     * Get the comments for the blog post.
     */
    public function images()
    {
        return $this->hasMany('App\ProductImage');
    }
}
然后,您可以通过执行以下操作来检索与产品关联的所有图像:

$images = App\Product::find(1)->images;
创建新的
产品
时,您还可以通过执行以下操作直接将
产品映像
与其关联:

$product->images()->createMany([
    ['path' => 'path-to-file.jpg',],
    ['path' => 'path-to-file.jpg',],
]);

如果您使用的是laravel Elequent,我建议您使用一对多(多态性)
您可以查看doc

非常感谢您的回复。我很好地定义了这些关系。但我需要的帮助是如何在将图像保存到数据库时获取产品id。这是我在ProductImage controller中的存储函数
if($request->hasFile($file')){foreach($request->file as$file){$filename=$file->getClientOriginalName();$filesize=$file->getClientSize();$file->storeAs($public/images',$filename);$ProductImage=new ProductImage();$productImage->name=$filename;$productImage->size=$filesize;$productImage->save();}}
。希望它清楚。你的问题不太清楚。如何获得
产品id
完全取决于您。例如,它可能是表单中的隐藏输入,也会在请求中提交。非常感谢。非常感谢。
$product->images()->createMany([
    ['path' => 'path-to-file.jpg',],
    ['path' => 'path-to-file.jpg',],
]);