嗨,我是Laravel的新手,目前正在使用Laravel 4.2。我试图创建一个应用程序,我有用户,帖子和评论表,并有以下模型
用户模型function posts() {
return $this->hasMany('Post');
}
function comments(){
return $this->hasMany('Comment');
}
Post模型function users() {
return $this->belongsTo('User');
}
function comments() {
return $this->hasMany('Comment');
}
评论模型
function posts(){
return $this->belongsTo('Post');
}
function users(){
return $this->belongsTo('User');
}
我想要达到的目标:
用户的帖子和对帖子的评论
eg:: User1 -> Post one -> comment for post one
我已经做了什么:::
$user = User::find(1);
$post = $user->posts()->get();
我能够得到帖子,但我如何得到特定帖子的评论??
感谢@Bogdan的帮助,我能够为用户获得帖子和评论。但像往常一样又有一个问题。
我得到了什么:
foreach($user->post AS $post) {
foreach ($post->comment AS $comment ) {
$comment->commentcontent; $user->uername;
}
}//first foreach
这是我得到的
comment one by user1.
comment two by user1.
但实际上注释1是user1创建的,注释2是user2创建的。
提前感谢您的帮助。可以张贴完整的代码,如果需要。
当您使用$user->posts()->get()
检索用户的帖子时,您将获得Models
的Collection
,您可以使用find
获取您想要的特定帖子。然后,您可以像检索用户的帖子一样检索帖子的评论:
$user = User::find(1);
$post = $user->posts()->find($postId);
$comments = $post->comments;
如果您想遍历整个帖子集合,您可以这样做,并单独访问每个帖子的评论,而不需要过滤特定的帖子:
foreach ($user->posts as $post)
{
$comments = $post->comments;
}
另外,为了将来参考,作为属性访问关系将返回一个Collection,而作为方法访问关系将返回一个Query Builder实例。所以$user->posts
和$user->posts()->get()
是一样的
您想要获取发表评论的用户,那么从评论对象中获取该用户。
试试这个
$user = User::find(1);
$posts = $user->posts;
foreach ($posts as $post) {
foreach ($post->comments as $comment) {
echo $comment->commentcontent;
echo $comment->users;
}
}
继续wiseodd
的答案。你可以急切加载posts
,以防止N + 1问题。
$user = User::with('posts.comments')->find($post_id);
$posts = $user->posts;
foreach ($posts as $post) {
foreach ($post->comments as $comment) {
echo $comment->commentcontent;
echo $comment->users;
}
}