Laravel Eloquent ORM firstOrNew大规模分配例外

时间:2014-08-28 16:52:24

标签: php laravel laravel-4 eloquent

我试图在基于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');
        }

}

1 个答案:

答案 0 :(得分:3)

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);