Des*_*ods 31 php eloquent laravel-5
我对laravel很新,我正在尝试从表单的输入更新记录.但是我看到要更新记录,首先需要从数据库中获取记录.是不是可能更新记录(主键设置):
$post = new Post();
$post->id = 3; //already exists in database.
$post->title = "Updated title";
$post->save();
Run Code Online (Sandbox Code Playgroud)
KaJ*_*asB 73
Post::where('id',3)->update(['title'=>'Updated title']);
Run Code Online (Sandbox Code Playgroud)
Bag*_*wan 33
您可以简单地使用查询生成器而不是Eloquent,此代码直接更新数据库中的数据:)这是一个示例:
DB::table('post')
->where('id', 3)
->update(['title' => "Updated Title"]);
Run Code Online (Sandbox Code Playgroud)
您可以在此处查看文档以获取更多信息:http://laravel.com/docs/5.0/queries#updates
har*_*rry 20
使用属性exists:
$post = new Post();
$post->exists = true;
$post->id = 3; //already exists in database.
$post->title = "Updated title";
$post->save();
Run Code Online (Sandbox Code Playgroud)
以下是API文档:http://laravel.com/api/5.0/Illuminate/Database/Eloquent/Model.html
maz*_*tch 16
常见的方式是加载要更新的行:
$post = Post::find($id);
Run Code Online (Sandbox Code Playgroud)
我你的情况
$post = Post::find(3);
$post->title = "Updated title";
$post->save();
Run Code Online (Sandbox Code Playgroud)
但是在一个步骤中(只需更新),您可以执行以下操作:
$affectedRows = Post::where("id", 3)->update(["title" => "Updated title"]);
Run Code Online (Sandbox Code Playgroud)
您也可以使用firstOrCreateORfirstOrNew
// 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();
Run Code Online (Sandbox Code Playgroud)
希望它能对您有所帮助:)