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

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)

  • 确认,这是 Eloquent 更新方式,无需执行 fetch (3认同)
  • 我希望这个答案首先显示,因为它是正确的答案 - 使用 Eloquent,而不是 Query Builder。 (2认同)

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

  • 不,因为那样你就失去了你的时间戳和其他模特行为 (4认同)
  • @malhal见KaJasB的下面回答,任何想要使用eloquent进行更新的人. (3认同)

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)

  • 他想避免获取记录。我来这里是因为我有一个循环,我想在其中更新一些行,我无法获取记录,这太乱了,而且最重要的是效率低下 (2认同)

Rav*_*ani 6

您也可以使用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)

希望它能对您有所帮助:)