Laravel 雄辩更新记录,无需从数据库加载

我对幼虫感到很陌生,我正在尝试从表格的输入更新一个记录。但是,我认为要更新记录,首先需要从数据库中获取记录。 对于更新记录(设置主键)这样的事情是不可能的:

$post = new Post();
$post->id = 3; //already exists in database.
$post->title = "Updated title";
$post->save();
246053 次浏览

The common way is to load the row to update:

$post = Post::find($id);

In your case

$post = Post::find(3);
$post->title = "Updated title";
$post->save();

But in one step (just update) you can do this:

$affectedRows = Post::where("id", 3)->update(["title" => "Updated title"]);

Use property exists:

$post = new Post();
$post->exists = true;
$post->id = 3; //already exists in database.
$post->title = "Updated title";
$post->save();

Here is the API documentation: http://laravel.com/api/5.0/Illuminate/Database/Eloquent/Model.html

You can simply use Query Builder rather than Eloquent, this code directly update your data in the database :) This is a sample:

DB::table('post')
->where('id', 3)
->update(['title' => "Updated Title"]);

You can check the documentation here for more information: http://laravel.com/docs/5.0/queries#updates

Post::where('id',3)->update(['title'=>'Updated title']);

You can also use 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();

Hope it will help you :)