我想在我的帖子中添加標簽。(拉拉博客)所以我創建了一個包含兩列的表,第一列是 post_id,第二列是 tag_id,這兩列都是外鍵?,F在我想顯示每個帖子的標簽,但我不知道如何獲取表格信息。這是我的遷移文件 public function up() { Schema::create('post_tag', function (Blueprint $table) { $table->unsignedBigInteger('post_id')->index(); $table->foreign('post_id')->references('id')->on('posts')->onUpdate('cascade')->onDelete('cascade'); $table->unsignedBigInteger('tag_id')->index(); $table->foreign('tag_id')->references('id')->on('tags')->onUpdate('cascade')->onDelete('cascade'); }); }那么如何在我的 postController 中獲取post_tag表信息以在視圖中顯示它們呢? public function getHomeIndex(){ $posts = Post::orderBy('created_at', 'desc')->paginate(9); $tags = ?????? return view('blog.index', ['posts' => $posts], 'tags' => $tags); }或者我做錯了,有更好的方法來發送標簽?
1 回答

30秒到達戰場
TA貢獻1828條經驗 獲得超6個贊
在 Post 模型中定義tag關系
public function tags()
{
return $this->belongsToMany(Tag::class, 'post_tag');
}
在控制器使用中
public function getHomeIndex()
{
$posts = Post::orderBy('created_at', 'desc')->with('tags')->paginate(9);
return view('blog.index', ['posts' => $posts]);
}
在視圖中
@foreach($posts as $post)
// post data here
@foreach($post->tags as $tag)
// $tag related data here
@endforeach
@endforeach
- 1 回答
- 0 關注
- 131 瀏覽
添加回答
舉報
0/150
提交
取消