Laravel Eloquent 使用 Create 保存到数据库 - 无用的错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22338149/
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-09-14 09:10:11  来源:igfitidea点击:

Laravel Eloquent Save to DB Using Create - Unhelpful Error

phplaraveleloquent

提问by sterfry68

I get a very unhelpful error when I try and insert a new record in to my db. Does anyone have any idea where to start to solve this error?

当我尝试在我的数据库中插入一条新记录时,我得到了一个非常无用的错误。有谁知道从哪里开始解决这个错误?

user_id

That's all it says. (This is the name of one of my required fields in the table I'm saving to but it's not very descriptive.)

这就是它所说的。(这是我要保存到的表中必填字段之一的名称,但它的描述性不强。)

For reference here's my code:

供参考,这是我的代码:

$data = array(
    'user_id'=>1,
    'post_type'=>'0',
    'post_title'=>'blah',
    'description'=>'blah');

//it fails on this line
$id = Post::create($data);

Here's what my model looks like:

这是我的模型的样子:

class Post extends Eloquent{
    public static $rules = array(
        'user_id'=>'required',
        'post_type'=>'required',
        'post_title' => 'required|max:25',
        'description'=>'required'
    );

    public static function validate($data){
        return Validator::make($data, static::$rules);
    }

    public function user(){
        return $this->hasOne('User', 'id', 'user_id');
    }
}

Tried getting rid of all relationships and validation in the model. That didn't work.

试图摆脱模型中的所有关系和验证。那没有用。

回答by gpopoteur

This is called mass-assignment in Laravel, what you need to do to get it working on your model is to set a protected array called $guardedto be empty. Add this to your model.

这在 Laravel 中称为批量赋值,要使其在模型上运行,您需要做的是将一个受保护的数组设置$guarded为空。将此添加到您的模型中。

protected $guarded = array();

What this array does, it can prevent attributes to be mass-assigned with an array, if you don't want an attribute to be filled with the Model::create()method, then you need to specify that attribute in the $guardedarray.

这个数组的作用是,它可以防止用数组批量分配属性,如果您不想用Model::create()方法填充属性,则需要在$guarded数组中指定该属性。

If instead you want to specify only the fillable attributes, Laravel's Eloquent also provides an array called $fillablewhere you specify only the attributes that you want to fill via the mass-assigment way.

如果您只想指定可填充的属性,Laravel 的 Eloquent 还提供了一个名为的数组$fillable,您可以在其中仅指定要通过批量分配方式填充的属性。

Further reading:

进一步阅读:

Mass Assignment: http://laravel.com/docs/eloquent#mass-assignment

批量分配:http: //laravel.com/docs/eloquent#mass-assignment

Create Method: http://laravel.com/docs/eloquent#insert-update-delete

创建方法:http: //laravel.com/docs/eloquent#insert-update-delete