插入子表

时间:2015-11-09 17:46:25

标签: eloquent laravel-5.1

我正在尝试将产品图像插入名为product_images的子表中,但它一直试图在products表中找到列'path'。

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'path' in 'field list'

以下是我设置控制器/模型的方法。

产品型号

public function category()
{
   return $this->belongsTo('App\Category');
}

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

产品图片

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

产品控制器

$product = new Product(); $product->category_id = $request->category_id; $product->name = $request->name; $product->price = $request->price;

//upload image
if ($request->hasFile('image')) {
    //validate
    $this->validate($request, [
        'image' => 'mimes:jpeg,bmp,png'
    ]);

    $image = $request->image;
    $filename = time() . '-' . $image->getClientOriginalExtension();
    $path = public_path('img/products/' . $filename);
    Image::make($image->getRealPath())->resize(468, 249)->save($path);
    $product->path = 'img/products/' . $filename;
}

$product->images()->save($product);

2 个答案:

答案 0 :(得分:0)

你应该使用

$product->images->path = 'img/products/' . $filename;

您可以使用push方法保存模型及其所有关系

$product->push();

答案 1 :(得分:0)

原来我需要这样做:$ image = new ProductImage();

然后$ product-> images() - > save($ image);

相关问题