【发布时间】:2019-09-27 04:22:12
【问题描述】:
我正在创建活动信息系统并希望在帖子/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();
});
创建类别表
Schema::create('categories', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->timestamps();
});
创建标签表
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>
【问题讨论】:
标签: php mysql laravel laravel-5 eloquent