我对laravel很新,我试图从表单的输入更新记录。但是我发现要更新记录,首先需要从数据库中获取记录。 是不是可以像更新记录(设置主键):Laravel雄辩的更新记录没有从数据库加载
$post = new Post();
$post->id = 3; //already exists in database.
$post->title = "Updated title";
$post->save();
我对laravel很新,我试图从表单的输入更新记录。但是我发现要更新记录,首先需要从数据库中获取记录。 是不是可以像更新记录(设置主键):Laravel雄辩的更新记录没有从数据库加载
$post = new Post();
$post->id = 3; //already exists in database.
$post->title = "Updated title";
$post->save();
您可以简单地使用查询生成器,而不是口若悬河,这个代码直接在数据库中更新数据:)这是一个示例:
DB::table('post')
->where('id', 3)
->update(['title' => "Updated Title"]);
您可以检查这里的文档的详细信息:http://laravel.com/docs/5.0/queries#updates
首先你需要加载该行更新:
$post = Post::find($id);
我你的情况
$post = Post::find(3);
$post->title = "Updated title";
$post->save();
他不想更新之前运行'select'查询。 – harrrrrrry
@zairwolf:这个答案没有错。这也是获取记录对象和更新特定字段的好方法。 –
他想避免提取记录。我来到这里是因为我有一个循环,我想更新一些行,我无法获取记录,它会太乱,最重要的是效率低下 – ggderas
使用属性exists
:
$post = new Post();
$post->exists = true;
$post->id = 3; //already exists in database.
$post->title = "Updated title";
$post->save();
这里的API文档:http://laravel.com/api/5.0/Illuminate/Database/Eloquent/Model.html
这正是我所期待的,谢谢! – oskarth
Post::where('id',3)->update(['title'=>'Updated title']);
这是正确的答案。 –
您还可以使用firstOrCreate
OR firstOrNew
// Retrieve the Post by the attributes, or create it if it doesn't exist...
$post = Post::firstOrCreate(['id' => 3]);
// OR
// Retrieve the Post by the attributes, or instantiate a new instance...
$post = Post::firstOrNew(['id' => 3]);
// update record
$post->title = "Updated title";
$post->save();
希望它会帮助你:)
感谢百万..你让我的一天 –
@KuHyeSun很高兴它适合你!干杯! –
不,因为这样你就失去了你的时间戳和其他模型行为 – malhal