
Laravel Eloquent ORM 提供多种便捷方法删除数据库记录。以下介绍几种常用的删除模型的方式:
1. 删除单个模型
使用 delete() 方法删除单个模型记录:
<code class="php">use App\Models\Post; // 查找记录 $post = Post::find(1); // 删除记录 $post->delete();</code>
注意:删除后,记录将永久从数据库中移除。
2. 删除多条记录
使用 delete() 方法结合 where 条件删除多条记录:
<code class="php">use App\Models\Post;
// 删除状态为 'draft' 的所有记录
Post::where('status', 'draft')->delete();</code>3. 使用 destroy() 方法
destroy() 方法可以删除单个或多个记录,直接使用主键ID:
<code class="php">use App\Models\Post; // 删除单个记录 Post::destroy(1); // 删除多个记录 Post::destroy([2, 3, 4]);</code>
注意:destroy() 方法仅接受主键ID作为参数。
4. 模型事件处理
Eloquent 提供了 deleting 和 deleted 事件,允许在删除记录前后执行自定义操作:
<code class="php"><?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Log;
class Post extends Model
{
protected static function booted()
{
static::deleting(function ($post) {
// 删除前执行的操作
Log::info('Post is being deleted: ' . $post->id);
});
static::deleted(function ($post) {
// 删除后执行的操作
Log::info('Post deleted: ' . $post->id);
});
}
}</code>5. 软删除
软删除不会物理删除记录,而是将 deleted_at 列设置为当前时间戳。 要启用软删除,在模型中使用 SoftDeletes 特性:
<code class="php"><?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Post extends Model
{
use SoftDeletes;
protected $dates = ['deleted_at'];
}</code>执行软删除:
<code class="php">use App\Models\Post; // 执行软删除 $post = Post::find(1); $post->delete(); // 将在 deleted_at 列中添加时间戳</code>
恢复软删除的记录:
<code class="php">// 查找软删除的记录 $post = Post::withTrashed()->find(1); // 恢复记录 $post->restore();</code>
强制删除(彻底删除):
<code class="php">$post->forceDelete(); // 永久删除记录</code>
查询软删除记录:
withTrashed():检索软删除和未删除的记录。onlyTrashed():仅检索软删除的记录。6. 直接使用数据库查询删除
可以使用 Laravel 的 DB facade 直接执行 SQL 查询删除记录:
<code class="php">use Illuminate\Support\Facades\DB;
// 使用原生SQL查询删除
DB::table('posts')->where('status', 'draft')->delete();</code>选择哪种删除方法取决于你的具体需求。 对于大多数情况,delete() 和 destroy() 方法已经足够了。 如果需要更精细的控制或需要软删除功能,则可以使用模型事件和 SoftDeletes 特性。 直接使用数据库查询通常用于更复杂的删除操作。
以上就是Bangla 部分删除模型中的 Laravel Eloquent ORM)的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号