我需要知道laravel 5save()
和create()
函数的区别是什么。在哪里可以使用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()接受完整的Eloquent模型实例
$comment = new App\Comment(['message' => 'A new comment.']);
$post = App\Post::find(1);
$post->comments()->save($comment);
创建()
create()接受纯PHP数组
$post = App\Post::find(1);
$comment = $post->comments()->create([
'message' => 'A new comment.',
]);
编辑
@PawelMysior指出,在使用create方法之前,请确保标记其值可以通过批量分配安全设置的列(例如name,birate_date等),我们需要通过提供更新来更新Eloquent模型一个名为$ fillable的新属性。这只是一个数组,其中包含可以通过批量分配安全设置的属性名称:
例子:-
class Country extends Model {
protected $fillable = [
'name',
'area',
'language',
];
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句