首页 > 解决方案 > 从 Laravel 中的逗号分隔值中获取流行标签

问题描述

我有标签表和新闻表。新闻表有 tag_id 表作为外键,如果新闻有超过 1 个标签,则以逗号分隔值存储。我想要的是获取那些有更多新闻的标签。 在此处输入图像描述

例如: 在上面的新闻表中: Tag id 1 共有 5 条新闻 Tag id 2 共有 4 条新闻 Tag id 3 共有 3 条新闻,Tag id 4 共有 2 条新闻。

所以,我想按以下顺序从最高新闻数到最低新闻数中获取热门标签:

  1. 政治
  2. 健康
  3. 犯罪
  4. 新冠病毒

我怎么做?请帮我!

标签: laravel

解决方案


The best way to implement this in laravel is by using Many to Many relationship. Create a news_tag pivot table with news_id & tag_id as columns. Then attach the tags upon creating news. Let me share an example with Articles & Tags.

class Article extends Model
{    
    public function tags(){
    return $this->belongsToMany(Tag::class);
}

}

Then your tag Model:

class Tag extends Model{
  public function articles(){
    return $this->belongsToMany(Article::class);
  }
}

Then your pivot table will look like this:

class CreateArticleTagTable extends Migration
{

public function up()
{
    Schema::create('article_tag', function (Blueprint $table) {
        $table->id();
        $table->unsignedBigInteger('article_id');
        $table->unsignedBigInteger('tag_id');
        $table->timestamps();

        $table->foreign('article_id')
            ->references('id')
            ->on('articles')
            ->onDelete('cascade');

        $table->foreign('tag_id')
            ->references('id')
            ->on('tags')
            ->onDelete('cascade');    
    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
  {
    Schema::dropIfExists('article_tag');
  }
}

Then in your controller attach the tags. you will need to get the tag id from the tags table and pass it to the view then on your store function post the id and attach it to news_tag like this.

  public function store(Request $request)
{
    $this->validate($request, [
        'heading' => 'required|string|max:191',
        'tag_id' => 'required|integer',
    ]);

    if($request->isMethod('post')){
        $article = new Article;
        $article->heading = $request['heading'];
        $article->tag_id = $request['tag_id'];
        $article->save();
        //attach tags
        $article->tags()->attach(request('tag_id'));

    }
}

推荐阅读