[英]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.