我尝试使用 Laravel 的 firstOrNew
方法保存数据,该方法会产生 MassAssignmentException
错误。
我不明白为什么 firstOrNew
方法应该触发批量分配异常,因为它只是查看数据库,而不是尝试保存任何内容。来自 the docs :
The firstOrNew method, like firstOrCreate will attempt to locate a record in the database matching the given attributes. However, if a model is not found, a new model instance will be returned. Note that the model returned by firstOrNew has not yet been persisted to the database.
为什么我的代码会抛出 MAE:
$tour = Tour::firstOrNew(array('id' => $this->request['id']));
据我了解,上面的代码所说的基本上都是“查看数据库中是否有具有该 ID 的行,如果有,则返回该行,如果没有,则创建一个具有相关 ID 的新对象”特性”。它没有保存任何数据,那么问题是什么?
请注意,仅当该行不存在时才会发生错误。
最佳答案
firstOrNew()
使用newInstance()
它使用构造函数创建新模型。 Constructor uses fill()
方法就是批量分配。这就是为什么你会遇到异常(exception)。
因此,您需要设置 $fillable
数组才能使用 firstOrNew()
关于Laravel MassAssignmentException 来自firstOrNew by id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40888273/