[英]Laravel Eloquent ORM firstOrNew mass assignment exception
I'm trying to look up a model in my database based on 2 fields, and if it doesn't exist, create a new model which contains those two values. 我试图基于2个字段在数据库中查找模型,如果不存在,请创建一个包含这两个值的新模型。 I'm attempting to use the firstOrNew
method to achieve this: 我正在尝试使用firstOrNew
方法来实现此目的:
$store = Store::firstOrNew(array('ext_hash' => $ext_hash, 'ext_type_id' => EXT_TYPE_ID));
However, this code is throwing a MassAssignmentException
. 但是,此代码将抛出MassAssignmentException
。
Is the only way to avoid this exception to assign fillable
properties on the class level? 避免此异常的唯一方法是在类级别分配fillable
属性? According to the documentation, I should be able to assign fillable
properties on the instance level, rather than for the entire class, but how would I do that? 根据文档,我应该能够在实例级别而不是整个类上分配fillable
属性,但是我该怎么做呢?
Here's the code for the Store
model: 这是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()
is the method you need: 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);
or: 要么:
$store = new Store;
$store = ($store->where($search)->first()) ?: $store->fillable(array_keys($search))->fill($search);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.