我正在尝试根据 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);
关于php - Laravel Eloquent ORM firstOrNew 批量赋值异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25554082/