
Laravel Eloquent 提供便捷的模型插入和更新数据库表数据的方法。以下详细介绍其使用方法。
模型插入 (添加数据)
save() 方法)save() 方法用于创建并保存 Eloquent 模型。
<code class="php">use App\Models\Post; // 创建新文章 $post = new Post(); $post->title = '新博客文章'; $post->content = '这是文章内容。'; $post->status = '草稿'; // 保存数据 $post->save();</code>
save() 方法在为模型赋值后调用,从而在数据库中创建新记录。
create() 方法)create() 方法直接将数据插入单行。
<code class="php">use App\Models\Post;
Post::create([
'title' => '快速博客文章',
'content' => '这是内容。',
'status' => '已发布',
]);</code>注意:使用 create() 方法时,请在模型中定义可填充或受保护属性。
<code class="php"><?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $fillable = ['title', 'content', 'status'];
}</code>insert() 方法一次性插入多条记录。
<code class="php">use App\Models\Post;
Post::insert([
['title' => '文章 1', 'content' => '内容 1', 'status' => '已发布'],
['title' => '文章 2', 'content' => '内容 2', 'status' => '草稿'],
]);</code>模型更新 (更新数据)
save() 方法)从数据库获取模型后,即可更新其数据。
<code class="php">use App\Models\Post; // 查找记录 $post = Post::find(1); // 更新数据 $post->title = '已更新的博客文章'; $post->status = '已发布'; // 保存 $post->save();</code>
update() 方法更新update() 方法直接更新多列。
<code class="php">use App\Models\Post;
Post::where('id', 1)->update([
'title' => '更新后的标题',
'status' => '已发布',
]);</code>update() 方法也可用于更新多条记录。
<code class="php">use App\Models\Post;
Post::where('status', '草稿')->update(['status' => '已存档']);</code>无需检索的插入或更新 (upsert)
upsert() 方法用于添加新数据或更新现有数据,无需先检索记录。
<code class="php">use App\Models\Post;
Post::upsert([
['id' => 1, 'title' => '更新标题 1', 'status' => '已发布'],
['id' => 2, 'title' => '更新标题 2', 'status' => '草稿'],
], ['id'], ['title', 'status']);</code>时间戳和软删除处理
Laravel 默认更新 created_at 和 updated_at 列。
<code class="php">$post = Post::find(1); $post->status = '已存档'; $post->save(); // `updated_at` 列自动更新</code>
如果模型启用了软删除,deleted_at 列将被更新,而不是删除数据。
<code class="php">$post->delete(); // 软删除</code>
批量插入和更新最佳实践
<code class="php">DB::transaction(function () {
Post::create([...]);
Post::update([...]);
});</code>$fillable 或 $guarded 属性。以上就是孟加拉语中的 Laravel Eloquent ORM 部分 - 插入和更新模型)的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号