dongyun3335 2014-04-26 13:20
浏览 46
已采纳

Laravel“where”查询具有渴望加载和关系

I'm currently trying to do a custom forum software for a client, and I'm using the laravel framework. The "board" contains "discussions" that haveMany "comments". Each discussion belongsTo a "category".

What I'm trying to do now, is creating an overview by category. Categories are predefined (like "news", "internal", "project" ...) and discussions can be assigned to them (the category is nullable).

The controller method to get the discussions by category, searching by the url-slug looks as follows:

return View::make('pages.board.overview', [
    'discussions', DiscussionCategory::where('slug', $slug)->discussions()->paginate(25)
]);

Except, that it doesn't work. I would like to retrieve all discussions (with their author, normally I would have used ::with('author'), but where do add that in this case?) that have the specified category, paginated by 25 items.

How do I build a query that does that? Is it even possible to do it in one query?

  • 写回答

1条回答 默认 最新

  • doufu8127 2014-04-26 13:42
    关注

    This will work:

    DiscussionCategory::where('slug', $slug)->with('discussions.author')->paginate(25)
    

    Set foreign key on the relation:

    // Discussion model, the same applies to the Category model
    public function category()
    {
        return $this->belongsTo('Umc\Models\DiscussionCategory', 'category_id');
    }
    

    Paginating discussions:

    $category = DiscussionCategory::where('slug', $slug)->first();
    $discussions = $category->discussions()->paginate(25);
    $discussions->load('author'); // eager load authors on the collection
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥15 统计大规模图中的完全子图问题
  • ¥15 使用LM2596制作降压电路,一个能运行,一个不能
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错
  • ¥20 @microsoft/fetch-event-source 流式响应问题
  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式