Laravel Eloquent saveMany不接受第二个属性

时间:2017-03-18 12:31:46

标签: php laravel-5 eloquent array-map savemany

我认为它通常是documentaion,我试图将saveMany作为模型对象的参数使用。{/ p>

我有一个名为Set的模型,hasMany Equipment因此,从创建一个集合的我提交了许多Equipment字段以便保存如下:

//Store method of SetController
$set = new Set();
        $set->title = request('title');
        $set->eqtype_id = request('eqtype');
        $set->product_id = request('product');
        $set->parts_count = request('parts_count');
        $eq = request('equipments');
        $set->equipments()->saveMany(array_map(function($n){return new \App\Equipment(['title' => $n, 'eqtype_id' => request('eqtype')]);}, $eq));
        $set->save();

但是,我总是收到有关eqtype_id没有默认值的错误消息:

  

SQLSTATE [HY000]:常规错误:1364字段'eqtype_id'没有   默认值(SQL:插入equipmentstitleset_id,   updated_atcreated_at)值(A-1,2017-03-18 12:07:30,   2017-03-18 12:07:30))

我认为,可能是request('eqtype')无法从array_map回调中访问,因此我将其替换为固定数字,如下所示:

$set->equipments()->saveMany(array_map(function($n){return new \App\Equipment(['title' => $n, 'eqtype_id' => 1]);}, $eq));

但错误也是一样的,它似乎是saveManyarray_map的问题。我不知道如何解决这个问题!

注意

模型Equipment与模型SetEqytpe相关,如下所示:

    //Equipment model
       <?php

namespace App;

use Illuminate\Database\Eloquent\Model;

/**
 * App\Equipment
 *
 * @mixin \Eloquent
 */
class Equipment extends Model
{
    public $table = "equipments";
    protected  $fillable = ['title'];
    public function set()
    {
      return $this->belongsTo(Set::class);
    }

    public function eqtype()
    {
      return $this->belongsTo(Eqtype::class);
    }

1 个答案:

答案 0 :(得分:0)

我遇到了同样的问题,这就是我为解决它所做的:

我在产品和图像之间建立了一对多的关系,我想在产品创建中添加与其相关的所有图像

// Create post
public function store(Request $request)
{
        $newProduct = Product::create([
        'name' => $request->name,
        'description' => $request->description,
        'price' => $request->price,
        'stock_items' => $request->stock_items,
    ]);


    for ($i = 0; $i < count($request->image_path); $i++) {
        $newProduct->image()->saveMany([

            new Image(['image_path' => $request->image_path[$i]])

        ]);
    }
}

不要忘记关系函数 & 创建多个同名输入:name='image_path[]'