2014-04-26 69 views
0

我目前正在尝试为客户端做一个自定义论坛软件,我使用laravel框架。 “董事会”包含“讨论”,有许多“评论”。每个讨论都属于“类别”。Laravel“哪里”查询与渴望加载和关系

我现在想要做的是按类别创建概览。类别是预定义的(如“新闻”,“内部”,“项目”...),并且可以将分配给它们(该类别可以为空)。

控制器的方法,按类别得到讨论,由URL段塞搜索看起来如下:

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

除此之外,它不工作。我想检索所有与其作者有关的讨论(通常我会使用::with('author'),但是在这种情况下还会添加哪些内容?),它们具有指定类别,由25个项目分页。

如何建立一个查询来做到这一点?是否可以在一个查询中执行?

回答

1

这将工作:在关系

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

设置外键:

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

分页讨论:

$category = DiscussionCategory::where('slug', $slug)->first(); 
$discussions = $category->discussions()->paginate(25); 
$discussions->load('author'); // eager load authors on the collection 
+0

哇,好不好......几乎工程。我只是得到了这个错误:'SQLSTATE [42S22]:未找到列:1054'where子句'中的未知列'board_discussions.discussion_category_id'(SQL:select * from'board_discussions',其中'board_discussions'.'leleted_at'为null并且(1)中的board_discussions'.'discussion_category_id') – spaceemotion

+0

然后,您的关系设置不正确。请展示讨论模型。 –

+0

好的,这里是讨论模型:http://hastebin.com/onaxosurel.php,这里是类别模型:http://hastebin.com/sunegokiqi.php – spaceemotion