How to insert in Laravel?

♀尐吖头ヾ 提交于 2019-12-08 09:39:15

问题


I have output object $product after inserting data into table Product:

$product = Product::create($data);

In model Product I have:

public function images()
    {
        return $this->hasMany("App\ProductImage");
    }

The I try to add images to table product_images:

$product->images()->save(new ProductImage(UploadFiles::$files));

Relationship beetwen tables is product.id = product_images.

So, after inserting I get message:

General error: 1364 Field 'image' doesn't have a default value (SQL: insert into `product_images` (`product_id`) values (21))

回答1:


OK, firstly let's deal with saving one image:

Assuming you have a product_images table with id, image, product_id, you would attach an image like so:

$image = new ProductImage(['image' => 'myImage.jpg']);
$product->images()->save($image);

Now it looks like you have an array, so you can't save that directly, you need to put it in a for loop. I don't know the format of your UploadFiles::$files, but I'll assume it's just a list of file names to save:

$files = UploadFiles::$files;

foreach($files as $file){
  $image = new ProductImage(['image' => $file]);
  $product->images()->save($image);
}

Alternatively, you could create the whole thing as an array and use saveMany, which would be better:

$files = UploadFiles::$files;
$productImages = [];

foreach($files as $image){
  $productImages[] = new ProductImage(['image' => $image]);
}

$product->images()->saveMany($productImages);


来源:https://stackoverflow.com/questions/40202421/how-to-insert-in-laravel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!