【问题标题】:Laravel Eloquent saveMany does not accept second attributeLaravel Eloquent saveMany 不接受第二个属性
【发布时间】:2017-03-18 12:31:45
【问题描述】:

我认为它通常与 documentaion 一样,我尝试使用 saveMany 将其参数作为模型对象。

我有一个名为 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: 插入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));

但错误也是一样的,这似乎是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);
    }

【问题讨论】:

  • 我在查询的INSERT 语句中没有看到eqtype_id
  • @JaredFarrish 这是我问题的核心!为什么eqtype_id 不存在,尽管我在array_map 中输入了它?!
  • @JaredFarrish 查看问题的更新。我把它加进去了。
  • 我没有看到定义了$this-&gt;eqtype_id 列,只有eqtype() 方法;将该数组传递给 Equipment 的构造函数会做什么?
  • 我会说这看起来与传入数据时如何实例化设备对象有关。

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


【解决方案1】:

我有同样的问题,这就是我解决它的方法:

我在产品和图片之间有一对多的关系,我想在产品创建时添加与之相关的所有图片

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-29
    • 2014-06-17
    • 2019-08-10
    • 2022-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多