我正在尝试在个人资料页面上显示用户评论所属的帖子标题。
这就是我在用户个人资料中所做的事情
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
获取了所有内容 - 但是,我无法在用户个人资料页面上显示这些评论所属的帖子
我可以在$comment->post_id
中使用foreach()
,但这只会获得帖子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...
Post
模型
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');
}
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');
}
User
模型
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');
}
答案 0 :(得分:2)
试试这个:
$comment->posts->title
(注意它是“帖子”而不是“帖子”)
您的评论模型具有posts
功能,因此当您从评论中访问它时,您可以使用该函数名称访问它,如上所示。
我会将帖子重命名为帖子,因为评论属于ONE帖子,而不是多个帖子。
同时更改
$user = User::whereName($user)->with('posts.votes')->with('comments')->firstOrFail();
是
$user = User::whereName($user)->with('posts.votes', 'comments.posts')->firstOrFail();