简体   繁体   中英

Insert foreign key data in database

I have two tables.

A product table and another product_image table. A product can have many images and a product`s image can only have a single image.

So,

For ProductImage model

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

For product model

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?

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() .

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 :

//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. 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;
    ?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM