[英]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:插入
equipments
(title
、set_id
、updated_at
、created_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));
但錯誤也是一樣的,這似乎是saveMany
或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);
}
我遇到了同樣的問題,這就是我為解決它所做的:
我在產品和圖像之間有一對多的關系,我想在產品創建中添加與其相關的所有圖像
// 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.