laravel 5.8雄辩:具有很多关系模型

时间:2019-09-27 04:22:12

标签: php mysql laravel laravel-5 eloquent

我正在创建事件信息系统,并希望在posts / show.blade.php中显示标签。

但是我出错了。

  

此集合实例上不存在属性[名称]

在帖子表中,我有category_id。 然后创建了post_tag表。

我需要创建另一个新表吗?

  

如何在show.blade.php中显示标签?

请帮帮我。

post.php

   public function tags() 
{
    return $this->belongsToMany(Tag::class);

}
public function hasTag($tagId)
    {
        return in_array($tagId, $this->tags->pluck('id')->toArray());
    }

tag.php

public function posts()
{
    return $this->belongsToMany(Post::class);
}

category.php

public function posts()
{
    return $this->hasMany(Post::class);
}

create_posts_table

Schema::create('posts', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('image');
        $table->unsignedBigInteger('category_id');
        $table->string('organizer');
        $table->string('title');
        $table->string('place');
        $table->string('map');
        $table->date('date');
        $table->timestamp('published_at')->nullable();
        $table->text('description');
        $table->timestamps();
    });

create_categories表

Schema::create('categories', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('name');
        $table->timestamps();
    });

create_tags表

Schema::create('tags', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('name');
        $table->timestamps();
    });

post_tag表

Schema::create('post_tag', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->integer('post_id');
        $table->integer('tag_id');
        $table->timestamps();
    });

ResultsControllere.php

public function show($id,Post $post)
{
    $post= Post::find($id);
    $post->category;
    $post ->tags;
    return view('posts.show',compact('post'));
}

show.blade.php

Tags:
  <div class="tags">
     {{ $post->tags->name }}
 </div>

2 个答案:

答案 0 :(得分:2)

根据您定义的关系post has many tags,因此您无法直接访问one to many relationship,您可能必须经过loop才能获取标签详细信息,例如名称

<div class="tags">
     @foreach($post->tags as $tag)
     {{ $tag->name }}
     @endforeach
</div>

谢谢。

答案 1 :(得分:2)

$post->tags应该返回一个集合,因此没有属性name

您的show.blade.php代码应为:

<div class="tags">
    @foreach($post->tags as $tag)
        {{ $tag->name }}
    @endforech
</div>
相关问题