laravel 5中的save(),create()函数有什么不同

Nik*_* K. 17 laravel laravel-5 laravel-5.2

我需要知道laravel 5 的区别save()create()功能是什么.我们可以使用save()create()

Ton*_*ent 26

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;
}
Run Code Online (Sandbox Code Playgroud)

保存()

  • save()方法既用于保存新模型,也用于更新现有模型.在这里,您正在创建新模型或查找现有模型,逐个设置其属性,最后保存在数据库中.

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

    $comment = new App\Comment(['message' => 'A new comment.']);
    
    $post = App\Post::find(1);
    
    $post->comments()->save($comment);
    
    Run Code Online (Sandbox Code Playgroud)


创建()

  • 在create方法中,您传递数组,在模型中设置属性并一次性保存在数据库中.
  • create()接受一个普通的PHP数组

    $post = App\Post::find(1);
    
    $comment = $post->comments()->create([
        'message' => 'A new comment.',
    ]);
    
    Run Code Online (Sandbox Code Playgroud)

    编辑
    正如@PawelMysior指出的那样,在使用create方法之前,一定要标记通过质量赋值设置值的列(例如name,birth_date等),我们需要通过以下方式更新我们的Eloquent模型提供一个名为$ fillable的新属性.这只是一个数组,其中包含可通过质量分配安全设置的属性名称:ex: -

    class Country extends Model {

    class Country extends Model {
    
        protected $fillable = [
            'name',
            'area',
            'language',
            ];
    }
    
    Run Code Online (Sandbox Code Playgroud)

    }

  • 这里要注意的一件重要事情是:如果你打算使用`create()`,你传递给它的所有属性都必须列在模型的`$ fillable`属性中.请参阅:https://laravel.com/docs/master/eloquent#mass-assignment (5认同)