删除 Laravel 5.2 中的关系关系



我正在尝试删除模型关系的关系。如果这有什么意义吗?

$post->comments()->activities()->delete();

所以我的帖子模型有评论,评论有活动。每当我尝试执行此操作时,都会收到此错误:

Call to undefined method IlluminateDatabaseQueryBuilder::activities()

我知道这有效:

$post->load('comments.activities');
foreach ($post->comments as $comment) {
    $comment->activities()->delete();
    $comment->delete();
}

但我认为第一个解决方案看起来更干净。有谁知道为什么这行不通?谢谢。

编辑

帖子

模型中的关系方法(多态,因为帖子上有评论和评论评论)。

public function comments()
{
    return $this->morphMany('AppModelsComment', 'commentable');
}

注释模型中的关系方法(多态,因为我在多个模型上使用活动)。

public function activities()
{
   return $this->morphMany('AppModelsActivity', 'subject');
}

尝试

$post->comments->activities()->delete();

当然,这只有在两个模型上都有一对多关系时才有效

你在写之前有没有给出表定义??

protected $table = 'posts';

你能详细说明一下你的问题吗?

最新更新