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()接受一个普通的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)
}
| 归档时间: |
|
| 查看次数: |
17211 次 |
| 最近记录: |