如何通过给定的项目ID将多张图片保存到表格中?

问题描述 投票:0回答:1

我是Laravel的新手。这与Laravel one to many类似

我有少于10张图片插入图片表,其中图片的外键为“item_id”。我想在“picture_name”中插入几个图片名称,其中“item_id”是2或7(任何项目)。

但我收到如下错误。有帮助吗?谢谢!

我的控制器代码:

$uploadPicture = array();

    foreach( $pictures as $picture )
    {

        $destinationPath = public_path().'/assets/img';
        $fileName = $picture->getClientOriginalName();
        $uploadSuccess = $picture->move($destinationPath, $fileName);


        $pictureModel = new Picture;
        array_push($uploadPicture, new Picture(array('picture_name' => $fileName)));
    }

    $item = Item::find($item->id);

    $item->pictures()->saveMany($uploadPicture);


    if($item->save() && $item->pictures()->saveMany($uploadPicture))
    {
        echo "<pre>".var_dump(Input::file('pictures'))."</pre>";
    }

我的型号代码:

class Item extends Eloquent {
protected $fillable = [];


/**
 * [pictures description]
 * @return [type] [description]
 */
public function pictures()
{
    return $this->hasMany('Pictures');

}

}

<?php


class Picture extends Eloquent {
protected $fillable = [];

public function items()
{
    return $this->belongsTo('Item');
}

}

解决方案:添加受保护的代码$ fillable = ['picture_name'];到图片模型。

php laravel
1个回答
2
投票

在你的Picture模型中添加:

protected $fillable = ['picture_name'];

Laravel提供质量分配保护,因此您必须指定$guarded$fillable才能使用质量分配数组创建/更新模型。

参考:http://laravel.com/docs/4.2/eloquent#mass-assignment

© www.soinside.com 2019 - 2024. All rights reserved.