1

I am using Laravel Commentable that uses Baum

Post Model

class Post extends Model
{
    use Commentable;
....

My user model name is User

Comment table structure:

enter image description here

The user_id stores the user id of the user who commented, commentable_id stores the post id of the post where the comment was placed. The Comments are working as expected. I am able to insert comments, delete comments.

To display the comments:

$comments = Comment::orderBy('id', 'desc')->get();

@foreach($comments as $comment)
    {{ $comment->user->name }} : {{ $comment->body }}
@endforeach

This gives me the name and the comment by the user in the view.

Question: How to get the post model attributes from a comment?

{{ $comment->post->slug }} <-this doesn't works

4

1 回答 1

1

根据此包中的代码,您必须使用commentable关系。但是,无法确定这将是一个Post模型,它可以是任何可评论的模型。

检查commentable是否实际上是post对象并显示slug的示例:

@if ($comment->commentable_type === \App\Post::class)
    {{ $comment->commentable->slug }} 
@endif
于 2017-08-11T06:35:10.623 回答