php Laravel eloquent 更新记录,无需从数据库加载

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29594572/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 00:28:51  来源:igfitidea点击:

Laravel eloquent update record without loading from database

phpeloquentlaravel-5

提问by Dester Dezzods

I'm quite new to laravel and I'm trying to update a record from form's input. However I see that to update the record, first you need to fetch the record from database. Isn't is possible to something like to update a record (primary key is set):

我对 laravel 很陌生,我正在尝试从表单的输入中更新记录。但是我看到要更新记录,首先需要从数据库中获取记录。不可能更新记录(设置主键):

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

回答by KaJasB

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

回答by Bagaskara Wisnu Gunawan

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

您可以简单地使用 Query Builder 而不是 Eloquent,此代码直接更新数据库中的数据:) 这是一个示例:

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

您可以在此处查看文档以获取更多信息:http: //laravel.com/docs/5.0/queries#updates

回答by harrrrrrry

Use property exists:

使用属性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

这是 API 文档:http: //laravel.com/api/5.0/Illuminate/Database/Eloquent/Model.html

回答by Ravi Hirani

You can also use firstOrCreateOR firstOrNew

您也可以使用firstOrCreatefirstOrNew

// 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 :)

希望它会帮助你:)

回答by maztch

The common way is to load the row to update:

常见的方式是加载要更新的行:

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

I 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"]);