简体   繁体   English

在数据库中插入外键数据

[英]Insert foreign key data in database

I have two tables. 我有两张桌子。

A product table and another product_image table. 一个product表和另一个product_image表。 A product can have many images and a product`s image can only have a single image. 一个产品可以有很多图像,而一个产品的图像只能有一个图像。

So, 所以,

For ProductImage model 对于ProductImage模型

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

For product model 对于product型号

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

I have made foreign key relation using migration. 我已经使用迁移建立了外键关系。

Now what I am unable to do is 现在我无法做的是

I am trying to upload an image for specific product. 我正在尝试上传特定产品的图片。 how can I get the id of the product to insert in product_id of productImage table? 如何获取要插入到productImage表的product_id中的productid

You have one-to-many relationship here, the relations between your models are true, i have just a small commentary for the function image() in your product model that should be pluriel images() . 您在这里有一对多的关系,您的模型之间的关系是真实的,我对您的product模型中的函数image()只是一个简短的评论,应该是pluriel images()

Now for the implementation you have first to create a product and start to associate images to it, so like this you don't have to worry about product_id , you have just to use associate method that will set the foreign key on the child model, see example bellow : 现在,对于实现,您首先需要创建一个产品并开始将图像与该产品相关联,因此您不必担心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();

Hope this helps. 希望这可以帮助。

This is not the exact result but it will help you to understand how to get last inserted id. 这不是确切的结果,但是它将帮助您了解如何获取最后插入的ID。 example: 例:

    <?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