简体   繁体   English

Laravel - 批量分配异常错误

[英]Laravel - Mass Assignment Exception error

I am trying to save multiple rows to a table, however, I am presented with a Mass Assignment Error .我正在尝试将多行保存到表中,但是,出现了Mass Assignment Error

The error is: Illuminate \\ Database \\ Eloquent \\ MassAssignmentException criteria_id错误是: Illuminate \\ Database \\ Eloquent \\ MassAssignmentException criteria_id

$criteria->save();

    $criteria_id = $criteria->id;

     foreach(Input::get('bedrooms') as $bedroom){
        $new_bedroom=array(
            'criteria_id' => $criteria->id,
            'bedroom' => $bedroom,
            );
        $bedroom = new Bedroom($new_bedroom);
        $bedroom->save();
    }

My database structure is:我的数据库结构是:

截屏

so there isn't any incorrect spelling.所以没有任何不正确的拼写。 The criteria_id comes from the variable from the recently saved criteria (see code above forloop).标准 ID 来自最近保存的标准的变量(请参阅上面的 forloop 代码)。

Any help would be greatly appreciated.任何帮助将不胜感激。

To be able to set properties by passing them to the model's constructor, you need to list all the properties you need in the $fillable array.为了能够通过将属性传递给模型的构造函数来设置属性,您需要在$fillable数组中列出您需要的所有属性。 As mentioned in the Docs文档中所述

class Bedroom extends Eloquent {
    protected $fillable = array('criteria_id', 'bedroom');
}

Also you can use the create method if you want.如果需要,您也可以使用create方法。 It creates a new model and saves it directly:它创建了一个新模型并直接保存:

foreach(Input::get('bedrooms') as $bedroom){
    $new_bedroom=array(
        'criteria_id' => $criteria->id,
        'bedroom' => $bedroom,
        );
    $bedroom = Bedroom::create($new_bedroom);
}

The inverse of what lukas said is "guarded".与卢卡斯所说的相反的是“守卫”。 Instead of "white-listing" fields, you could just declare which are guarded.而不是“白名单”字段,您可以声明哪些是受保护的。

For example:例如:

class Bedroom extends Model
{
    protected $guarded = ['id'];
}

This was more useful for me because I didn't really care about most fields.这对我更有用,因为我并不真正关心大多数领域。

Gotten from the docs for Laravel 5.2 but I assume it works on older versions.来自 Laravel 5.2 的文档,但我认为它适用于旧版本。

To allow any fields, you could just provide an empty array:要允许任何字段,您只需提供一个空数组:

class Bedroom extends Model
{
    protected $guarded = [];
}

Write the code in the Model that you want to store your data on that table.在模型中编写要在该表上存储数据的代码。 Suppose your table is bedrooms and you created model is Bedroom which is located in the app folder.假设你的桌子是卧室,你创建的模型是卧室,它位于app文件夹中。

In your case, you have to store data in $criteria_id and $bedroom , so you should add these two fields to the model in the following way.在您的情况下,您必须将数据存储在$criteria_id$bedroom ,因此您应该按以下方式将这两个字段添加到模型中。

class Bedroom extends Model 
{
    protected $fillable = ['criteria_id', 'bedroom'];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM