[英]Laravel Eloquent ORM firstOrNew mass assignment exception
我試圖基於2個字段在數據庫中查找模型,如果不存在,請創建一個包含這兩個值的新模型。 我正在嘗試使用firstOrNew
方法來實現此目的:
$store = Store::firstOrNew(array('ext_hash' => $ext_hash, 'ext_type_id' => EXT_TYPE_ID));
但是,此代碼將拋出MassAssignmentException
。
避免此異常的唯一方法是在類級別分配fillable
屬性? 根據文檔,我應該能夠在實例級別而不是整個類上分配fillable
屬性,但是我該怎么做呢?
這是Store
模型的代碼:
<?php
use Illuminate\Database\Eloquent\SoftDeletingTrait;
class Store extends Eloquent{
use SoftDeletingTrait;
public function products(){
return $this->hasMany('Product');
}
public function faqs(){
return $this->hasMany('ProductFaq');
}
public function customer_questions(){
return $this->hasMany('CustomerQuestion');
}
public function users(){
return $this->hasMany('User');
}
}
fillable()
是您需要的方法:
$search = array('ext_hash' => $ext_hash, 'ext_type_id' => EXT_TYPE_ID);
$store = (Store::where($search)->first())
?: with(new Store)->fillable(array_keys($search))->fill($search);
要么:
$store = new Store;
$store = ($store->where($search)->first()) ?: $store->fillable(array_keys($search))->fill($search);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.