我想显示帖子的标签,但是当我尝试显示时,标签只出现在最后一个帖子中。
这是我的代码;
博客 Controller ;
public function getSingle($slug){
$posts = Post::where('slug', $slug)->first();
return view('front.pages.single')->with('post', $posts);
}
Single.blade.php
<div class="blog-main">
{!! $post->body !!}
<hr>
@if($post->tags()->count() == 0)
{{"Add Some Tags"}}
@elseif($post->tags()->count() > 0)
<p> <strong>Tags:</strong>
@foreach($post->tags as $tag)
<span class="btn btn-outline-primary btn-sm" ><a href="{{route('tags.show',$tag->id)}}" >{{$tag->name}} </a></span>
@endforeach </p>
@endif
</div>
与标签和帖子的关系
后模型
public function tags(){
return $this->belongsToMany('App\Tag');
}
标签模型
public function posts(){
return $this->belongsToMany('App\Post');
}
我哪里弄错了?
最佳答案
后模型
public function tags(){
return $this->hasMany('App\Tag', 'foreign_id');
}
标签模型
public function post(){
return $this->belongsTo('App\Post', 'foreign_id);
}
你的 Blade 弄错了。
<div class="blog-main">
{!! $post->body !!}
<hr>
@if($post->tags->count() == 0)
{{"Add Some Tags"}}
@elseif($post->tags->count() > 0)
<p> <strong>Tags:</strong>
@foreach($post->tags as $tag)
<span class="btn btn-outline-primary btn-sm" ><a href="{{route('tags.show',$tag->id)}}" >{{$tag->name}} </a></span>
@endforeach </p>
@endif
</div>
关于php - 拉维尔 5.5 |标签只出现在最后一篇文章中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47094877/