lundi 21 octobre 2019

Laravel How to insert data to 2 tables which has foreign key to each other

I have 3 tables: stocks, colors and images;

colors has a foreign key on stocks

and images has a foreign key on colors like this

Stocks:

id    | name     
-------------------------
1     | Berlin - Paris 
2     | Madrid - London
3     | Berlin - Paris 

Colors:

id    | stocks_id | icon
---------------------------------------
1     |     1     | img1.png  
2     |     2     | img2.png  
3     |     3     | img3.png  

Images:

id    |  color_id | url
---------------------------------------
1     |     1     | img1.png  
2     |     2     | img2.png  
3     |     3     | img3.png  

I'm using a Model to insert the stocks to the database and attach() to create the color with the belongsTo relationship.

How to insert the images using attach() with a foreign key to colors ???

I've tried many things with attach() but I've stuck with it for 2 months



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire