为什么只有在我在模型上加上 ::withTrashed() 时才能识别我的条目?

huangapple go评论57阅读模式
英文:

Why is my entry only recognized only when I put ::withTrashed() on the model

问题

这个问题是关于在用户创建时设置deleted_at日期为一小时后以实现软删除的功能,但问题是Eloquent已经将该条目标记为软删除。如何在不将deleted_at设置为null的情况下解决这个问题。

以下是解决方法:

这段代码是有效的:

$user = User::withTrashed()->where('id', 15)->first();

而这段代码则无效:

$user = User::where('id', 15)->first(); // 返回null

在你的模型文件中,这是用于在创建时设置deleted_at时间的代码:

public static function boot()
{
    parent::boot();

    static::creating(function ($model) {
        $model->deleted_at = now()->addHour();
    });
}

这个问题的原因是,当你使用User::where('id', 15)->first()时,Eloquent 在查询时不会触发creating事件,因此deleted_at不会被设置,导致Eloquent将其标记为软删除。而使用User::withTrashed()允许你检索已软删除的记录,因此它有效。

要解决这个问题,你可以考虑使用以下方法之一:

  1. 使用User::create()方法创建用户,这样creating事件会被触发,deleted_at会正确设置。

  2. 手动设置deleted_at并保存用户,例如:

$user = new User();
$user->id = 15;
$user->deleted_at = now()->addHour();
$user->save();

这样你可以在不将deleted_at设置为null的情况下创建软删除记录。

英文:

So I am creating an user, on creation I set the deleted_at date a hour ahead so it softdeletes if the time passes, but the problem is that eloquent is already taking the entry as softdeleted.How do I fix this without making the deleted_at null.

This works:

$user = User::withTrashed()->where('id',15)->first();

And this does not:

$user = User::where('id',15)->first(); //returns null

This is my code for setting the deleted_at time on creation in the model file:

public static function boot()
{
    parent::boot();

    static::creating(function ($model) {
            $model->deleted_at = now()->addHour();
    });
}

答案1

得分: 2

软删除不是为此而设计;日期只是记录删除的时间。Laravel 的查询只是查找 deleted_at 中的 NULL 值;没有更复杂的东西。

你想要的是自己的全局作用域,可以应用于模型。你可以在其中使用 deleted_at,但最好使用类似 available_until 这样的东西来区分它们。

英文:

Soft deletions aren't made for this; the date is simply a record of when it was deleted. Laravel's queries just look for a NULL value in deleted_at; nothing fancier.

What you want is your own global scope you can apply to the model. You could use deleted_at in it, but you're probably better off with something like available_until to keep them separate.

huangapple
  • 本文由 发表于 2023年6月15日 21:51:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/76483190.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定