[英]Insert foreign key data in database
我有两张桌子。
一个product
表和另一个product_image
表。 一个产品可以有很多图像,而一个产品的图像只能有一个图像。
所以,
对于ProductImage
模型
public function product()
{
return $this->belongsTo('App\Models\Product');
}
对于product
型号
public function image()
{
return $this->hasMany('App\Models\ProductImage');
}
我已经使用迁移建立了外键关系。
现在我无法做的是
我正在尝试上传特定产品的图片。 如何获取要插入到productImage
表的product_id
中的product
的id
?
您在这里有一对多的关系,您的模型之间的关系是真实的,我对您的product
模型中的函数image()
只是一个简短的评论,应该是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();
希望这可以帮助。
这不是确切的结果,但是它将帮助您了解如何获取最后插入的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;
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.