代码之家  ›  专栏  ›  技术社区  ›  Saurabh

使用Laravel中的Baum获取可注释类属性

  •  1
  • Saurabh  · 技术社区  · 7 年前

    Laravel Commentable 使用 Baum

    Post模型

    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 }} <-这行不通

    1 回复  |  直到 7 年前
        1
  •  1
  •   Jerodev    7 年前

    Per the code from this package ,您必须使用 commentable 关系然而,无法确定这将是一个 Post

    一个示例,检查可注释对象是否实际上是post对象,如果是,则显示slug:

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