在Laravel中使用Baum获取可评论的类属性

时间:2017-08-11 06:18:18

标签: php mysql laravel laravel-collection

我正在使用使用Laravel Commentable

Baum

发布模型

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

我的用户型号名称为用户

评论表格式

enter image description here

user_id存储评论用户的用户ID,commentable_id存储评论所在帖子的帖子ID。 评论按预期工作。 我可以插入评论,删除评论。

显示评论:

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

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

这为我提供了视图中用户的姓名和评论。

问题: 如何从评论中获取帖子模型属性?

{{ $comment->post->slug }}< -this not not works

1 个答案:

答案 0 :(得分:1)

Per the code from this package,您必须使用commentable关系。但是,无法确定这将是Post模型,这可以是任何可评论的模型。

检查可评论是否真的是一个post对象并显示slug的例子:

@if ($comment->commentable_type === \App\Post::class)
    {{ $comment->commentable->slug }} 
@endif