【问题标题】:How best can i link product_id to images so the one product can have multiple images linked我如何最好地将 product_id 链接到图像,以便一个产品可以链接多个图像
【发布时间】:2018-12-30 02:15:53
【问题描述】:

我正在开发电子商务网站。我的产品上传很好,带有 1 张显示图像。我想在不同的表中单独上传多张图片,但通过 product_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


    【解决方案1】:

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

    这是一个例子。

    <?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');
        }
    }
    

    接下来,需要在App\ProductImage中定义逆关系

    <?php
    
    namespace App;
    
    use Illuminate\Database\Eloquent\Model;
    
    class ProductImage extends Model
    {
        /**
         * Get the comments for the blog post.
         */
        public function product()
        {
            return $this->belongsTo('App\Product');
        }
    }
    

    然后您可以通过执行以下操作来检索与产品关联的所有图像:

    $images = App\Product::find(1)->images;
    

    在创建新的Product 时,您还可以通过执行以下操作直接将ProductImage 与其关联:

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

    【讨论】:

    • 非常感谢您的回复。我已经很好地定义了关系。但我需要帮助的是如何在将图像保存到数据库时获取 product_id。这是我在 ProductImage 控制器if($request-&gt;hasFile('file')) { foreach ($request-&gt;file as $file) { $filename = $file-&gt;getClientOriginalName(); $filesize = $file-&gt;getClientSize(); $file-&gt;storeAs('public/images',$filename); $productImage = new ProductImage(); $productImage-&gt;name = $filename; $productImage-&gt;size = $filesize; $productImage-&gt;save(); } } 中的商店功能。希望它清楚。不知道格式化
    • 你的问题不是很清楚。如何获得product_id 完全取决于您。例如,它可能是表单中的隐藏输入,也会在请求中提交。
    • 非常感谢。非常感谢。
    【解决方案2】:

    如果你使用的是 laravel Elequent。使用一对多关系。一对多关系定义为单个模型拥有多个模型

    One To Many

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

    Query Builder

    【讨论】:

      【解决方案3】:

      我推荐你如果你使用 laravel Elequent 使用一对多(多态) 你可以看文档here

      【讨论】:

        猜你喜欢
        • 2011-06-30
        • 2014-11-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-02
        相关资源
        最近更新 更多