英文:
Laravel: the save method doesn't work in the booted function
问题
我想在对象创建或更新时创建或更新slug属性。对于对象的初始创建,我无法使用creating事件,因为我需要对象id。所以最终我将我的slug代码放在saved事件中,因为它适用于创建和更新操作。但看起来booted函数中的save方法导致我的浏览器一直加载。
class Discussion extends Model
{
use HasFactory;
...
protected static function booted(): void
{
static::saved(function (Discussion $discussion) {
$discussion->slug = Str::slug($discussion->subject, '-').'-' . $discussion->id;
$discussion->save(); // <= 这导致浏览器一直加载。
});
static::deleting(function (Discussion $discussion) {
$discussion->groups()->detach();
$discussion->registrations()->delete();
});
}
}
最终出现了这个错误:'child process still did not exit sending a sigterm',我不得不重新启动我的服务器。
不管怎样,显然问题来自于save方法。所以我想知道如果save方法不起作用,我该如何保存slug值?
英文:
I want to create or update a slug attribute whenever an object is created or updated.
For the initial creation of the object I can't use the creating event as I need the object id.
So I finally put my slug code in the saved event as it works for both create and update actions.
But it looks like the save method in the booted function causes my browser to load forever.
class Discussion extends Model
{
use HasFactory;
...
protected static function booted(): void
{
static::saved(function (Discussion $discussion) {
$discussion->slug = Str::slug($discussion->subject, '-').'-'.$discussion->id;
$discussion->save(); // <= This causes the browser loading forever.
});
static::deleting(function (Discussion $discussion) {
$discussion->groups()->detach();
$discussion->registrations()->delete();
});
}
}
It finally ended up with this error: child process still did not exit sending a sigterm
and I had to reboot my server.
Anyway, it's clear the probleme comes from the save method.
So I'm wondering how can I save the slug value if the save method doesn't work ?
答案1
得分: 2
您正在注册一个事件,每当模型被保存并且在该事件中保存模型时,就会触发该事件,从而创建一个循环。尝试不使用事件保存:
static::saved(function (Discussion $discussion) {
$discussion->slug = Str::slug($discussion->subject, '-') . '-' . $discussion->id;
$discussion->saveQuietly(); // <= 这不会导致浏览器一直加载。
});
英文:
Your are registering an event to trigger whenever the model is saved AND you save the model in that event, creating a loop. Try saving without events:
static::saved(function (Discussion $discussion) {
$discussion->slug = Str::slug($discussion->subject, '-').'-'.$discussion->id;
$discussion->saveQuietly(); // <= This does NOT causes the browser loading forever.
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论