簡體   English   中英

在數據庫中插入外鍵數據

[英]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中的productid

您在這里有一對多的關系,您的模型之間的關系是真實的,我對您的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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM