删除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) {
$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。

但如果帖子有100条评论,它将执行100条查询来删除它们!我会想出如何用最少的查询删除。。。

我已经在评论上有了onDelete,但通知是多态的,所以它对它们不起作用。。。

我将使用的解决方案是:
1-获取与帖子相关的评论的ID
2-从通知中删除,其中在(id(中键入IS Comment AND id
3-删除与帖子相关的评论
4-删除与帖子相关的通知
5-删除帖子。

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', 'AppComment')->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.
}
static::deleting(function($comment) {
$ids = $comment->notifications()->lists('id')->all();
Notification::destroy($ids);
});

链接将不起作用,因为模型没有初始化
最好的解决方案是循环并删除单个评论

static::deleting(function($post) {
foreach ($post->comments() as $comment){
$comment->delete();
}
});

请使用(假设帖子和评论之间的关系(

$table->foreign('post_id')
->references('id')->on('posts')
->onDelete('cascade');

以便在迁移文件中建立外部关系。所以当你删除相关的帖子时,它的评论也会被删除。

最新更新