1

我认为它通常是我尝试使用的关于其参数作为模型对象的文档。saveMany

我有一个名为的模型SethasMany Equipment因此,从创建一个集合的 from 中,我提交了许多字段,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 Field 'eqtype_id' doesn't have a default value (SQL: insert into equipments( title, set_id, updated_at, created_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));

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

注意

该模型Equipment与两个模型相关,Set如下Eqytpe所示:

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

1 回答 1

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[]'

于 2021-03-11T14:49:20.020 回答