我对 laravel 很陌生,我正在尝试从表单的输入中更新记录。但是我看到要更新记录,首先您需要从数据库中获取记录。不可能更新记录(设置了主键):
$post = new Post();
$post->id = 3; //already exists in database.
$post->title = "Updated title";
$post->save();
Post::where('id',3)->update(['title'=>'Updated title']);
您可以简单地使用 Query Builder 而不是 Eloquent,此代码直接更新数据库中的数据 :) 这是一个示例:
DB::table('post')
->where('id', 3)
->update(['title' => "Updated Title"]);
您可以在此处查看文档以获取更多信息:http://laravel.com/docs/5.0/queries#updates
if ($data->save())
?
使用属性 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
常见的方法是加载要更新的行:
$post = Post::find($id);
在你的情况下
$post = Post::find(3);
$post->title = "Updated title";
$post->save();
但一步(只需更新)您可以这样做:
$affectedRows = Post::where("id", 3)->update(["title" => "Updated title"]);
Without Loading
。您的答案是加载数据以更新它。
您也可以使用 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();
希望它会帮助你:)
DB::beginTransaction()
支持吗?DB::beginTransaction()
一起使用,因为它是修改表的语句,并且数据库引擎会将其解释为真正的事务。