【问题标题】:Laravel 4 - list posts collection only with associated commentsLaravel 4 - 仅列出带有相关评论的帖子集合
【发布时间】:2014-07-24 12:01:20
【问题描述】:

我正在尝试显示没有与之关联的 cmets 的帖子列表。换句话说,在我的一对多关系中,如果有孩子,帖子不应该显示。

除了使用原始查询进行此操作外,是否有一种简单的方法可以雄辩地做到这一点?

模型 - Post.php

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

模型 - Comment.php

 public function post()
    {
        return $this->belongsTo('Post');
    }

控制器 - PostController.php

public function unanswered()
{

    $posts = Post::with('comments')
        ->orderBy('created_at', 'desc')
        ->paginate(5);


    return View::make('unanswered')->with('posts',$posts);

}

【问题讨论】:

    标签: laravel laravel-4 eloquent


    【解决方案1】:

    为了获取具有或不具有给定关系的模型,您需要使用has 方法。

    根据您想要实现的目标,使用纯 has('relation') 或传递其他参数:

    $posts = Post::has('comments', '<', 1)->get();
    

    【讨论】:

    • 谢谢。我绝对应该知道这一点:-)
    【解决方案2】:

    with('cmets') 是预加载

    您需要的实际上是与 where 连接。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-17
      • 1970-01-01
      • 2014-10-13
      • 1970-01-01
      • 2011-07-24
      • 2014-08-02
      • 2016-12-02
      • 2017-07-29
      相关资源
      最近更新 更多