Laravel eloquent 更新记录而不从数据库加载
Laravel eloquent update record without loading from database
我是 laravel 的新手,我正在尝试根据表单输入更新记录。但是我看到要更新记录,首先你需要从数据库中获取记录。
更新记录之类的事情是不可能的(设置了主键):
$post = new Post();
$post->id = 3; //already exists in database.
$post->title = "Updated title";
$post->save();
常用的方式是加载要更新的行:
$post = Post::find($id);
你的情况
$post = Post::find(3);
$post->title = "Updated title";
$post->save();
但是一步之遥(只需更新),您可以这样做:
$affectedRows = Post::where("id", 3)->update(["title" => "Updated title"]);
使用属性 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
您可以简单地使用查询生成器而不是 Eloquent,此代码直接更新数据库中的数据:)这是一个示例:
DB::table('post')
->where('id', 3)
->update(['title' => "Updated Title"]);
您可以在此处查看文档以获取更多信息:http://laravel.com/docs/5.0/queries#updates
Post::where('id',3)->update(['title'=>'Updated title']);
您也可以使用 firstOrCreate
或 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();
希望对您有所帮助:)
我是 laravel 的新手,我正在尝试根据表单输入更新记录。但是我看到要更新记录,首先你需要从数据库中获取记录。 更新记录之类的事情是不可能的(设置了主键):
$post = new Post();
$post->id = 3; //already exists in database.
$post->title = "Updated title";
$post->save();
常用的方式是加载要更新的行:
$post = Post::find($id);
你的情况
$post = Post::find(3);
$post->title = "Updated title";
$post->save();
但是一步之遥(只需更新),您可以这样做:
$affectedRows = Post::where("id", 3)->update(["title" => "Updated title"]);
使用属性 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
您可以简单地使用查询生成器而不是 Eloquent,此代码直接更新数据库中的数据:)这是一个示例:
DB::table('post')
->where('id', 3)
->update(['title' => "Updated Title"]);
您可以在此处查看文档以获取更多信息:http://laravel.com/docs/5.0/queries#updates
Post::where('id',3)->update(['title'=>'Updated title']);
您也可以使用 firstOrCreate
或 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();
希望对您有所帮助:)