2

我有两张桌子。

一张product桌子和另一张product_image桌子。一个产品可以有很多张图片,而一个产品的图片只能有一张图片。

所以,

ProductImage型号_

public function product()
    {
        return $this->belongsTo('App\Models\Product');
    }

product型号_

public function image()
{
    return $this->hasMany('App\Models\ProductImage');
}

我已经使用迁移建立了外键关系。

现在我无法做的是

我正在尝试上传特定产品的图片。我怎样才能得到idproduct插入product_idproductImage表?

4

2 回答 2

1

你在这里有一对多的关系,你的模型之间的关系是真实的,我对image()你的product模型中应该是 pluriel的函数有一个小的评论images()

现在对于实现,您首先要创建一个产品并开始将图像与其关联,因此您不必担心product_id,您只需使用associate将在子模型上设置外键的方法,请参见示例波纹管:

//Creation of product
$product = Product::create(['Your attributes here']);

//Association of images
$product->images()->associate('Your image 1 here');
$product->images()->associate('Your image 2 here');
$product->images()->associate('Your image 3 here');

//To get the images associated with your product 
$product->images();

希望这可以帮助。

于 2015-10-08T17:27:12.660 回答
-1

这不是确切的结果,但它将帮助您了解如何获取最后插入的 id。例子:

    <?php
    $product = new Product; //create the object

    $product->image= 'Your_image'; // image column 

    $product->save(); //store data

    //Getting Last inserted id

    $insertedId = $product->id;
    ?>
于 2015-10-08T15:34:28.090 回答