首先,我从php和MVC框架开始,我仍然不是很擅长这个,我也不能对这个问题做很多研究,因为我真的不知道如何将其转化为谷歌搜索。
这也是为什么我的题目这么有趣
我有三个模型:Post, Comment和Comment
评论既属于帖子也属于评论,所以我在我的模型中有这段代码,它都很简单
class Post extends Eloquent {
public function comments() {
return $this->has_many('Comment');
}
}
…
class Commenter extends Eloquent {
public function comments () {
return $this->has_many('Comment');
}
}
…
class Comment extends Eloquent {
public function commenter () {
return $this->belongsTo('Commenter');
}
public function post () {
return $this->belongsTo('Post');
}
}
然后我想要一个查询只列出评论者,如果他们对给定的帖子有评论
我需要浏览评论列表,然后找到谁有属于那个帖子的评论。(我真的不需要担心是否最优,因为这是一个小的实验项目,有一个小数据库)
我不知道如何将此传递给使用控制器的视图,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']));
和View
@foreach($comments as $comment)
Author: <strong>{{$comment->commenter->name}}</strong>
@endforeach
或者你可以创建一个新的属性
class Post extends Eloquent {
public function getCommentersAttribute()
{
$comments = $this->comments;
foreach($this->comments as $comment)
{
/// do whatever you need to grab your list of commenters
}
return $yourListOfCommenters
}
}
然后你可以在任何你需要的地方引用它:
$post->commenters
我意识到不会有一个像我想要的那样简单的方法,所以我决定去一个新的多对多关系…
我添加了
public function posts () {
return $this->belongsToMany('Post');
}
和
public function commenters () {
return $this->belongsToMany('Commenter');
}
现在我可以简单地使用
->with ('commenters', Post::find($post_id)->commenters()->get())
在我的控制器中找到我的评论者列表
谢谢大家的帮助。