英文:
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()
允许你检索已软删除的记录,因此它有效。
要解决这个问题,你可以考虑使用以下方法之一:
-
使用
User::create()
方法创建用户,这样creating
事件会被触发,deleted_at
会正确设置。 -
手动设置
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论