laravel 5 中的 save()、create() 函数有什么不同 [英] What is different between save(), create() function in laravel 5

查看:30
本文介绍了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()查看实现

/**
 * 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() 方法用于保存新模型和更新现有的.在这里,您正在创建新模型或查找现有模型,一一设置其属性,最后保存到数据库中.

  • 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 AppComment(['message' => 'A new comment.']);

$post = AppPost::find(1);

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


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 = AppPost::find(1);

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

编辑
正如@PawelMysior 指出的那样,在使用 create 方法之前,一定要标记其值可以通过批量赋值安全设置的列(例如 name、birth_date 等),我们需要通过提供一个更新我们的 Eloquent 模型名为 $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天全站免登陆