我需要知道 laravel 5 中 save()
和 create()
函数有什么区别。
我们可以在哪里使用 save()
和 create()
?
最佳答案
Model::create
是一个简单的包装器 $model = new MyModel(); $模型->保存()
查看实现
/**
* 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、birth_date 等)。我们需要通过提供名为 $fillable 的新属性。这只是一个包含可通过批量赋值安全设置的属性名称的数组:
示例:-
class Country extends Model {
protected $fillable = [
'name',
'area',
'language',
];
}
关于laravel - Laravel 5 中的 save() 和 create() 函数有什么不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38843202/