我正在创建事件信息系统并希望在 posts/show.blade.php 中显示标签。
但是我得到一个错误。
Property [name] does not exist on this collection instance
在帖子表中,我有 category_id。 我创建了 post_tag 表。
我需要创建另一个新表吗?
How to show tags in 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());
}
标签.php
public function posts()
{
return $this->belongsToMany(Post::class);
}
类别.php
public function posts()
{
return $this->hasMany(Post::class);
}
创建帖子表
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'));
}
显示.blade.php
Tags:
<div class="tags">
{{ $post->tags->name }}
</div>
最佳答案
根据你定义的关系post有很多标签
所以你不能直接访问一对多关系
你可能必须循环
通过获取标签详细信息,例如名称
<div class="tags">
@foreach($post->tags as $tag)
{{ $tag->name }}
@endforeach
</div>
谢谢。
关于php - laravel 5.8 Eloquent : has many relations model,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58127847/