gpt4 book ai didi

php - 删除laravel中的一行时删除所有关系

转载 作者:行者123 更新时间:2023-12-01 01:40:09 27 4
gpt4 key购买 nike

我有帖子、评论和通知表

每个帖子都有很多评论

每条评论都有许多通知

每个帖子都有许多通知

class Post extends Model
{

public function notifications() {
return $this->morphOne(Notification::class, 'to');
}

public function comments() {
return $this->hasMany(Comment::class, 'post_id');
}

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

static::deleting(function($post) {
$post->comments()->delete();
$post->notifications()->delete();
});
}
}
class Comment extends Model
{
public function notifications() {
return $this->morphOne(Notification::class, 'to');
}

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

static::deleting(function($comment) {
$comment->notifications()->delete();
});
}
}

当我删除帖子时,我也应该删除通知和评论,
但问题是当我删除评论时,通知不会随之删除,
当我直接删除评论时,它们会被删除,但是当我删除帖子时,我需要删除评论的通知!

最佳答案

Laravel 不会实例化它删除的相关模型,这就是为什么直接删除评论时会删除通知,而删除帖子删除评论时则不会。删除帖子时,您必须实例化评论才能使其正常工作。

class Post extends Model {

public function notifications() {
return $this->morphOne(Notification::class, 'to');
}

public function comments() {
return $this->hasMany(Comment::class, 'post_id');
}

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

static::deleting(function($post) {
// here you could instantiate each related Comment
// in this way the boot function in the Comment model will be called
$post->comments->each(function($comment) {
// and then the static::deleting method when you delete each one
$comment->delete();
});
$post->notifications()->delete();
});
}
}

只是为了记录,我在评论中添加了我们讨论的内容,因为它可以为遇到相同问题的其他人提供服务,并且在评论中可能会被忽视。归功于 OP @Mahmoud Ben Jabir。

But if the post has 100 comments It will execute 100 query to delete them ! I will Figure out how to delete with minimum queries...

I already have onDelete on comments, but the notifications are polymorphic so it won't work on them...

The solution I will use is:
1- Get Ids of Comments that are related to the Post.
2- Delete from Notifications where type IS Comment AND id in (ids).
3- Delete Comments related to the Post.
4- Delete The Notifications Related to the Post
5- Delete The Post.

public static function boot() {
parent::boot();
static::deleting(function($post) {
// 1- Get Ids of Comments that are related to the Post.
$ids = $post->comments()->pluck('id');
// 2- Delete from Notifications where type IS Comment AND id in (ids).
Notification::where('entity_type', 'App\Comment')->whereIn('entity_id', $ids)->delete();
// 3- Delete Comments related to the Post.
$post->comments()->delete();
// 4- Delete The Notifications Related to the Post
$post->notifications()->delete();
});
// 5- Delete The Post.
}

关于php - 删除laravel中的一行时删除所有关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58955862/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com