laravel Eloquent firstOrCreate 文档或用法

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

Eloquent firstOrCreate documentation or usage

laravellaravel-4eloquent

提问by Clark T.

I'm attempting to seek a table to see if a column named "name" exists if so return the value and if not create that row with a null value i saw firstOrCreate but i cannot figure out how to use it for the life of me.

我正在尝试寻找一个表,以查看是否存在名为“name”的列,如果存在,则返回该值,如果不使用空值创建该行,我看到了 firstOrCreate 但我无法弄清楚如何在我的一生中使用它.

This is what i currently have, can someone lend a hand?

这是我目前拥有的,有人可以帮忙吗?

 class Settings extends Eloquent
        {
            protected $table = 'settings';
            protected $primaryKey = 'name';

            public static function get($settingName)
                {
                    return self::firstOrCreate(array('name' => $settingName));
//                    return self::select(array('value'))->where('name', '=', $settingName)->first()->value;
                }
        }

回答by Antonio Carlos Ribeiro

The create() method does mass assignment and this is a big security issue, so Laravel has a protection against it. Internally it has guarded = ['*'], so all your columns will be protected against mass assignment. You have some options:

create() 方法进行批量赋值,这是一个很大的安全问题,所以 Laravel 有一个保护措施。在内部,它已保护 = ['*'],因此您的所有列都将受到保护以防止批量分配。你有一些选择:

Set the fillable columns of your model:

设置模型的可填充列:

class User extends Eloquent {

    protected $fillable = array('first_name', 'last_name', 'email');

}

Or set only the ones you want to keep guarded:

或者只设置你想要保护的那些:

class User extends Eloquent {

    protected $guarded = array('password');

}

You may, at your own risk also do:

您也可以自行承担风险:

class User extends Eloquent {

    protected $guarded = array();

}

And everything will be unguarded.

一切都将毫无防备。

Take a look a the docs: http://laravel.com/docs/eloquent#mass-assignment

看看文档:http: //laravel.com/docs/eloquent#mass-assignment

You also could use your Facade to call it:

您也可以使用 Facade 来调用它:

 class Settings extends Eloquent
 {
        protected $table = 'settings';
        protected $primaryKey = 'name';

        public static function get($settingName)
        {
            return Settings::firstOrCreate(array('name' => $settingName));
        }
 }