Php Laravel雄辩ORM-返回对象,其中的对象也属于第三个对象

Php Laravel雄辩ORM-返回对象,其中的对象也属于第三个对象,php,model,controller,laravel,eloquent,Php,Model,Controller,Laravel,Eloquent,首先,我从php和MVC框架开始,我还不是很擅长这个,我也不能对这个问题做很多研究,因为我真的不知道如何将其转化为谷歌搜索 这也是为什么我的问题标题如此有趣的原因 好吧,假设我有三个模型:Post、Commenter和Comment 评论同时属于帖子和评论人,所以我的模型中有这段代码,非常简单 class Post extends Eloquent { public function comments() { return $this->has_many('Com

首先,我从php和MVC框架开始,我还不是很擅长这个,我也不能对这个问题做很多研究,因为我真的不知道如何将其转化为谷歌搜索

这也是为什么我的问题标题如此有趣的原因

好吧,假设我有三个模型:Post、Commenter和Comment

评论同时属于帖子和评论人,所以我的模型中有这段代码,非常简单

class Post extends Eloquent {

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

然后我想要一个查询,仅当评论者对给定帖子有评论时才列出他们

我需要浏览评论列表,然后找到谁有属于这篇文章的评论。(我真的不需要担心优化,因为这是一个带有小型数据库的小型实验项目)

我不知道如何使用控制器将其传递给视图,
Commenter::has('comments')
将显示任何在任何地方有注释的人,但我认为这是起点。我在文档中也找不到答案

如果我的问题不够清楚,请告诉我

class Comment extends Eloquent {

    public function commenter () { 
        return $this->belongsTo('Commenter');
    }

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

class Commenter extends Eloquent {

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

}

class Post extends Eloquent {

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

}
你可以

$post = Post::find($givenPostID);

View::make('posts.comments.listCommenters')
  ->with('commenters', $post->comments()->groupBy('commenter_id')->get(['commenter_id']));
在我看来

@foreach($comments as $comment)
  Author: <strong>{{$comment->commenter->name}}</strong>
@endforeach
然后,您只需在任何需要的地方引用它:

$post->commenters

我意识到没有一种方法像我想要的那么简单,所以我决定建立一种新的多对多关系

我补充说

public function posts () {
    return $this->belongsToMany('Post');
}

现在我可以简单地使用

->with ('commenters', Post::find($post_id)->commenters()->get())
在我的控制器中查找我的评论者列表


感谢您的帮助,所有回答的人。

请向我们提供您的
评论员
类。现在使用所有类编辑,但如果我这样做,它将列出同一作者两次,如果有多个评论员属于他。我需要先浏览一下评论者列表,找出谁有属于那个特定帖子的评论你是对的,但为了解决这个问题,我在上面添加了一个groupBy。我只是给你一些想法,并不是真正解决你的问题,如果你认为你需要浏览评论列表,然后获得所有的评论,你可能需要编写更多的代码,一个查询来为你这样做,或者在你的模型上创建一个新方法来获得评论列表。groupBy方法实际上可能很有用,谢谢你的主意,但我还是不知道它是否能帮我。要创建这个新方法,我必须做什么?只是编辑以添加属性。要创建方法,只需从方法名称中删除get*属性。谢谢!我会试着用它
$post->commenters
public function posts () {
    return $this->belongsToMany('Post');
}
public function commenters () {
    return $this->belongsToMany('Commenter');
}
->with ('commenters', Post::find($post_id)->commenters()->get())