如何在Laravel中插入? [英] How to insert in Laravel?

查看:87
本文介绍了如何在Laravel中插入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将数据插入表Product后,我具有输出对象$product:

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

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

在模型Product中,我有:

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

我尝试将图像添加到表product_images:

The I try to add images to table product_images:

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

关系beetwen表是product.id = product_images.

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

推荐答案

好的,首先让我们处理一个图像的保存:

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

假设您有一个包含idimageproduct_idproduct_images表,您将像这样附加图像:

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);

现在看来您有一个数组,因此您无法直接保存它,需要将其放入for循环中.我不知道您的UploadFiles::$files的格式,但我假设它只是要保存的文件名列表:

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);
}

或者,您可以将整个对象创建为数组并使用saveMany,这会更好:

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);

这篇关于如何在Laravel中插入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆