laravel - 从 Laravel 中的逗号分隔值中获取流行标签
问题描述
我有标签表和新闻表。新闻表有 tag_id 表作为外键,如果新闻有超过 1 个标签,则以逗号分隔值存储。我想要的是获取那些有更多新闻的标签。
例如: 在上面的新闻表中: Tag id 1 共有 5 条新闻 Tag id 2 共有 4 条新闻 Tag id 3 共有 3 条新闻,Tag id 4 共有 2 条新闻。
所以,我想按以下顺序从最高新闻数到最低新闻数中获取热门标签:
- 政治
- 健康
- 犯罪
- 新冠病毒
我怎么做?请帮我!
解决方案
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'));
}
}
推荐阅读
- excel - 从工作表导航到编辑栏的快捷方式/快捷方式
- bazel - 如何从 repository_ctx 运行 bazel 二进制可执行文件
- python - 默认和计算在甘特视图odoo14中不起作用
- php - 原始php嵌套菜单重定向问题
- javascript - Shopify-获取属性形式
- javascript - 仅在选择国家/地区时在搜索框中显示国家/地区标志
- r - 连接两个数据框并按组重复值
- flutter - 未处理的异常:对空值使用空检查运算符
- go - 如何使用 Cobra 和 Viper 将值绑定为配置中数组的第一项?
- three.js - Webgl/Three.js 抗锯齿问题