簡體   English   中英

Laravel Eloquent saveMany 不接受第二個屬性

[英]Laravel Eloquent saveMany does not accept second attribute

我認為它通常作為文檔,我嘗試使用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:插入equipmentstitleset_idupdated_atcreated_at )值(A- set_id 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);
    }

我遇到了同樣的問題,這就是我為解決它所做的:

我在產品和圖像之間有一對多的關系,我想在產品創建中添加與其相關的所有圖像

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM