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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动