php Laravel - 批量分配异常错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26724117/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 23:01:18  来源:igfitidea点击:

Laravel - Mass Assignment Exception error

phplaravellaravel-4eloquent

提问by lukasgeiter

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:

我的数据库结构是:

screenshot

截屏

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.

任何帮助将不胜感激。

回答by lukasgeiter

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 $fillablearray. As mentioned in the Docs

为了能够通过将属性传递给模型的构造函数来设置属性,您需要在$fillable数组中列出您需要的所有属性。如文档中所述

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

Also you can use the createmethod if you want. It creates a new model and saves it directly:

create如果需要,您也可以使用该方法。它创建了一个新模型并直接保存:

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

回答by csga5000

The inverseof 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 = [];
}