我试图在他的个人资料页面上显示用户评论所属的帖子标题。
这就是我在用户个人资料上所做的
public function show($user, Post $post)
{
$user = User::whereName($user)->with('posts.votes')->with('comments')->firstOrFail();
$comments = $user->comments;
$linkKarma = User::find($user->id)->votes()->sum('value');
$commentKarma = User::find($user->id)->commentvotes()->sum('value');
$total_comments = $user->comments->count();
$isModerator = false;
return view('user/profile')->with('user', $user)
->with('linkKarma', $linkKarma)
->with('commentKarma', $commentKarma)
->with('comments', $comments)
->with('total_comments', $total_comments)
->with('isModerator', $isModerator);
}
我基本上从posts
、votes
和comments
得到了他所有的东西 - 但是,我无法显示帖子这些评论属于用户个人资料页面。
我可以在 foreach()
中使用 $comment->post_id
但这只会让我得到帖子 ID 但我不能使用 $comment ->post->title
会报错 Trying to get a property of a none object
我该怎么做?
我的数据库
posts: id, title, user_id, subreddit_id...
comments: id, comment, user_id, post_id...
user: id, name, email...
发布
模型
public function user() {
return $this->belongsTo('App\User');
}
public function subreddit() {
return $this->belongsTo('App\Subreddit');
}
public function votes() {
return $this->hasMany('App\Vote');
}
public function moderators() {
return $this->hasMany('App\Moderator');
}
public function comments() {
return $this->hasMany('App\Comment');
}
注释
模型
public function posts() {
return $this->belongsTo('App\Post');
}
public function user() {
return $this->belongsTo('App\User');
}
public function commentvotes() {
return $this->hasMany('App\CommentVote');
}
public function subreddit() {
return $this->belongsTo('App\Subreddit');
}
用户
模型
public function subreddit() {
return $this->hasMany('App\Subreddit');
}
public function posts() {
return $this->hasMany('App\Post');
}
public function votes() {
return $this->hasManyThrough('App\Vote','App\Post');
}
public function commentvotes() {
return $this->hasManyThrough('App\CommentVote','App\Comment');
}
public function moderators() {
return $this->hasMany('App\Moderator');
}
public function comments() {
return $this->hasMany('App\Comment');
}
最佳答案
试试这个:
$comment->posts->title
(注意是“posts”不是“post”)
您的 Comment 模型具有函数 posts
,因此当您从评论中访问它时,您可以使用该函数名称访问它,如上所示。
我会将帖子重命名为 post,因为评论属于一个帖子,而不是多个帖子。
也改变
$user = User::whereName($user)->with('posts.votes')->with('comments')->firstOrFail();
成为
$user = User::whereName($user)->with('posts.votes', 'comments.posts')->firstOrFail();
关于php - 拉维尔 5 : show me the post title that this comment belongs to on user profile,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33323809/