php - Laravel Eloquent ORM firstOrNew 批量赋值异常

标签 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');
        }

}

最佳答案

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/

相关文章:

php - Laravel 4 Eloquent 按关系日期分组

php - MYSQL -> 获取每个 "group by"的最高值

php - Codeigniter 表单验证未显示错误

php - 特征不只是组合吗?

php - Laravel 准备语句 UPDATE 查询

php - 在编辑模式下使用 Laravel 数组表单复选框

javascript - 使用 JavaScript 显示订单总计

javascript - 从 laravel Controller 将值传递给 ajax 然后获取特定字段

php - Laravel 中具有多对多关系的工厂种子数据透视表

php - 如何在 laravel 中使用 joins 和 groupby 并进行迭代?