首页 > 解决方案 > Laravel如何将数据插入到彼此具有外键的2个表中

问题描述

我有 3 张桌子:股票颜色图像

颜色在股票上有外键

并且图像在 这样的颜色上有一个外键

股票:

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

颜色:

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

图片:

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

我正在使用模型将股票插入数据库并使用attach()创建具有belongsTo关系的颜色。

如何使用带有颜色外键的 attach() 插入图像???

我用attach()尝试了很多东西,但我坚持了 2 个月

我正在使用的代码:

$stock= new Stocks();
    $stock->storeColors()->attach($request->color_name, array('icon' => request('icon')));
//the line I need to write:
    $stock->storeColors()->storeImages()->attach($request->image);

标签: phpmysqllaravellaravel-5eloquent

解决方案


你可以这样做

$imagenes=[];

$stock= new Stocks();
  $data =  $stock->storeColors()->attach($request->color_name, array('icon' => request('icon')));


  $color = Color::where('stock_id',$data->id)->first();

  if ($request->hasFile('imagen')) {

          foreach ($request->imagen as $image) {

                 $imagenes[]=
                      new Images([
                         'url' => $image->url
                      ]);

      $request->file('imagen')->move('imagenes/','imagenName.jpg');

   }

 }

$color ->images()->saveMany($imagenes);

推荐阅读