Php 在laravel中查找与标记关联的所有帖子
我正在与laravel建立一个博客,其中一篇文章有许多标签。我想用标签过滤所有帖子。意思是如果我点击“PHP”标签,我想得到所有相关的帖子 这是我的代码Php 在laravel中查找与标记关联的所有帖子,php,mysql,laravel,laravel-5,eloquent,Php,Mysql,Laravel,Laravel 5,Eloquent,我正在与laravel建立一个博客,其中一篇文章有许多标签。我想用标签过滤所有帖子。意思是如果我点击“PHP”标签,我想得到所有相关的帖子 这是我的代码 public function up() { Schema::create('tags', function (Blueprint $table) { $table->increments('id'); $table->string('tags'); $table->t
public function up()
{
Schema::create('tags', function (Blueprint $table) {
$table->increments('id');
$table->string('tags');
$table->timestamps();
});
}
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');
});
}
我有两个表,第一个是标签表,第二个是帖子链接表
标签表
public function up()
{
Schema::create('tags', function (Blueprint $table) {
$table->increments('id');
$table->string('tags');
$table->timestamps();
});
}
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');
});
}
关系标记表
public function up()
{
Schema::create('tags', function (Blueprint $table) {
$table->increments('id');
$table->string('tags');
$table->timestamps();
});
}
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');
});
}
文章模型
class Article extends Model
{
public function tags()
{
return $this->belongsToMany('App\Tag');
}
}
class Tag extends Model
{
public function articles()
{
return $this->belongsToMany('App\Article');
}
}
标签型号
class Article extends Model
{
public function tags()
{
return $this->belongsToMany('App\Tag');
}
}
class Tag extends Model
{
public function articles()
{
return $this->belongsToMany('App\Article');
}
}
标签控制器
public function show($id,$name)
{
//here I received tag id and name.
$list->with('articles')->get();
return view('articles.tagshow')->withList($list);
}
Eloquent提供了whereHas方法,可用于过滤相关模型的属性。要按项目关联标记的名称筛选项目,应执行以下操作:
$articles = Article::whereHas('tags', function($query) use ($tagName) {
$query->whereName($tagName);
})->get();
但是,在您的情况下,它应该更简单,因为您的控制器中已经有了标记ID,因此您只需按ID获取标记模型,然后返回相关文章:
public function show($id,$name) {
return Tag::findOrFail($id)->articles;
}
查看有关查询关系的文档以了解更多详细信息:您是否阅读了雄辩的关系。如果不是,我建议你读一读,