我正在用 laravel 建立一个博客,其中一个帖子有很多标签。我想通过标签过滤所有帖子。意味着如果我单击“PHP”标签,我想获取所有相关的帖子。
这是我的代码
我有两个表,第一个用于标签,第二个表用于帖子链接
标签表
public function up()
{
Schema::create('tags', function (Blueprint $table) {
$table->increments('id');
$table->string('tags');
$table->timestamps();
});
}
Run Code Online (Sandbox Code Playgroud)
关系标签表
public function up()
{
Schema::create('article_tag', function (Blueprint $table) {
$table->increments('id');
$table->integer('article_id')->unsigned();
$table->foreign('article_id')->references('id')->on('articles');
$table->integer('tag_id')->unsigned();
$table->foreign('tag_id')->references('id')->on('tags');
});
}
Run Code Online (Sandbox Code Playgroud)
文章模型
class Article extends Model
{
public function tags()
{
return $this->belongsToMany('App\Tag');
}
}
Run Code Online (Sandbox Code Playgroud)
标签模型
class Tag extends Model
{
public function articles()
{
return $this->belongsToMany('App\Article');
}
}
Run Code Online (Sandbox Code Playgroud)
标签控制器
public function show($id,$name)
{
//here I received tag id and name.
$list->with('articles')->get();
return view('articles.tagshow')->withList($list); …Run Code Online (Sandbox Code Playgroud)