ChatGPT解决这个技术问题 Extra ChatGPT

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

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

$post = new Post();
$post->id = 3; //already exists in database.
$post->title = "Updated title";
$post->save();
这对遇到相同问题的新用户很有帮助:scratchcode.io/database-records-update-in-laravel

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

确认,这是无需执行 fetch 即可更新的 Eloquent 方式
我希望首先显示这个答案,因为它是正确的答案 - 使用 Eloquent,而不是 Query Builder。
如果出现问题,这会回滚吗?我的意思是,这受 DB::beginTransaction() 支持吗?
当然,它可以与 DB::beginTransaction() 一起使用,因为它是修改表的语句,并且数据库引擎会将其解释为真正的事务。
@Kajasb 是否有任何可以在没有新查询的情况下获取此更新记录?
B
Bagaskara Wisnu Gunawan

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

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

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


谢谢一百万..你让我开心
不,因为那样你会丢失你的时间戳和其他模型行为
@malhal 不幸的是,我还没有找到使用 Eloquent 修复这种情况的任何解决方案,因为 Eloquent 基本上为每一行创建对象,以便能够拥有所有这些功能。因此,要在不加载和更新每一行的情况下更新它们是根本不可能的。 CMIIW
在这种情况下,您如何检查给定行是否确实已更新?像if ($data->save())
@malhal 对于想要使用 eloquent 进行更新的任何人,请参阅 KaJasB 的以下回答。
h
harrrrrrry

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


老实说,这有点难读。
P
Prabhu

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

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

在你的情况下

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

但一步(只需更新)您可以这样做:

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

@zairwolf:这个答案没有错。这也是获取记录对象和更新特定字段的好方法。
他想避免获取记录。我来到这里是因为我有一个循环,我想在其中更新一些行,我无法获取记录,这太混乱了,最重要的是效率低下
首先阅读问题。发布问题的用户实际上已明确指出 Without Loading。您的答案是加载数据以更新它。
R
Ravi Hirani

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

希望它会帮助你:)