雄辩的获取行,其中关系计数等于列值

时间:2019-02-21 13:02:42

标签: mysql laravel orm eloquent

假设我的posts表具有字段minimum_comments并在posts表中具有查询范围,以使活动的帖子执行类似的操作

public function scopeActive($query)
{
    $query->has('comments', '>=', 'posts.minimum_comments');
}

考虑所有关系已建立

我该如何实现?

1 个答案:

答案 0 :(得分:1)

我还没有测试,但是尝试一下:

// Post.php

public function scopeActive($query)
{
    return $query->where('minimum_comments', '<=', $this->comments()->count());
}

然后您可以像这样使用它:

// PostsController.php

public function myCoolFunction()
{
    $posts = Post::active()->get();

    // the rest of your logic..
}
相关问题