Laravel 5中save(),create()函数之间的区别是什么 [英] What is different between save(), create() function in laravel 5

查看:561
本文介绍了Laravel 5中save(),create()函数之间的区别是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要知道laravel 5中save()create()函数的区别是什么 在哪里可以使用save()create()?

I need to know what is the difference of save() and create() function in laravel 5. Where we can use save() and create() ?

推荐答案

Model::create是围绕$model = new MyModel(); $model->save()的简单包装 查看实现

Model::create is a simple wrapper around $model = new MyModel(); $model->save() See the implementation

/**
 * Save a new model and return the instance.
 *
 * @param  array  $attributes
 * @return static
 */
public static function create(array $attributes = [])
{
    $model = new static($attributes);

    $model->save();

    return $model;
}

保存()

  • save()方法用于保存新模型和更新 现有的.在这里您要创建新模型或找到现有模型, 逐一设置其属性,最后保存在数据库中.

  • save() method is used both for saving new model, and updating existing one. here you are creating new model or find existing one, setting its properties one by one and finally saves in database.

save()接受完整的Eloquent模型实例

save() accepts a full Eloquent model instance

$comment = new App\Comment(['message' => 'A new comment.']);

$post = App\Post::find(1);

$post->comments()->save($comment);


create()


create()

  • 在创建方法时,您要传递数组,并在其中设置属性 建模并持久保存在数据库中.
  • create()接受纯文本 PHP数组

  • while in creating method you are passing an array, setting properties in model and persists in the database in one shot.
  • create() accepts a plain PHP array

$post = App\Post::find(1);

$comment = $post->comments()->create([
    'message' => 'A new comment.',
]);

编辑
正如@PawelMysior指出的那样,在使用create方法之前,请确保标记其值可以通过批量分配安全设置的列(例如name,birate_date等).我们需要通过提供一个名为$ fillable的新财产.这只是一个数组,其中包含可以通过批量分配安全设置的属性名称:

EDIT
As @PawelMysior pointed out, before using the create method, be sure to mark columns whose values are safe to set via mass-assignment (such as name, birth_date, and so on.), we need to update our Eloquent models by providing a new property called $fillable. This is simply an array containing the names of the attributes that are safe to set via mass assignment:

示例:-

class Country extends Model {

    protected $fillable = [
        'name',
        'area',
        'language',
        ];
}

这篇关于Laravel 5中save(),create()函数之间的区别是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆