php - Laravel 4.1 Eloquent - 过滤关系集合

标签 php orm laravel eloquent

我在使用 laravel 4.1 hasWhere 过滤关系时遇到问题。

迭代 1 - 获取所有帖子:完成

$posts = Post::all();

迭代 2 - 获取所有帖子延迟加载评论:完成

$posts = Post::with('comments')->get();

迭代 3 - 仅获取带有评论和延迟加载的帖子:完成

$posts = Post::with('comments')->has('comments')->get();

迭代 4 - 仅获取已发布评论和延迟加载的帖子:已损坏

$posts = Post::with('comments')
    ->whereHas('comments', function($q) {
        return $q->where('published', '=', 1);
    })
    ->get();

print_r($posts->toArray()) 的输出显示迭代 3 和 4 的输出完全相同。 我无法根据 'comments.published' = 1 条件过滤关系。

最佳答案

我找到了一个解决方案,但我不确定这是否是最优雅的解决方案。因此,我将此开放以寻求更好的建议。

    $posts = Post::
        ->whereHas('comments', function($q)
            {
                $q->where('published', '=', 1);
            })
        ->with([
            'comments' => function($q)
            {
                $q->where('published', '=', 1);
            },
            ])->get();

基本上,我的解决方案涉及过滤 Eloquent 结果,并单独过滤延迟加载。这是必要的吗?有没有更好的方法来实现这一目标?

关于php - Laravel 4.1 Eloquent - 过滤关系集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20933880/

相关文章:

php - Mysql/PHP错误: not displaying $username

php - MySqli INSERT 不起作用,没有错误

php - 如何设置旋转图像?

Laravel 多对多关系 sync() where

mysql - 使用 Django queryset 查询日期对象存在性能问题

php - 如何仅在 laravel 中使用 DATE 获取数据?

php - 路由到子文件夹中的 Controller 在 Laravel 4 中不起作用

php - Html form select blank 搜索其他字段匹配的所有表格

mysql - Doctrine2 返回 1 个元素的数组而不是 null

php - 拉维尔 5.5 : array_combine(): Both parameters should have an equal number of elements