gpt4 book ai didi

php - Laravel - belongsToMany 高效标签计数?

转载 作者:行者123 更新时间:2023-12-03 23:10:01 26 4
gpt4 key购买 nike

给定以下 belongsToMany 关系:

标签模型:

class Tag extends Model
{
public function posts (){
return $this->belongsToMany('App\Post');
}
}

后模型:

class Post extends Model
{
public function tags (){
return $this->belongsToMany('App\Tag');
}
}

在 Laravel 中查询每个标签的数量并根据标签数量从低到高排序的最有效和可扩展的方式是什么?

最佳答案

为了获取标签及其计数,您需要加入 tags 表以便使用 post_tag 表获取 Tag 数据以获取给定标签用于标记帖子的次数。您可以使用以下代码执行此操作:

// get Tag data and join with post_tag
$counts = Tag::join('post_tag', 'tags.id', '=', 'post_tag.tag_id')
// group by tags.id in order to count number of rows in join and to get each tag only once
->groupBy('tags.id')
// get only columns from tags table along with aggregate COUNT column
->select(['tags.*', DB::raw('COUNT(*) as cnt')])
// order by count in descending order
->orderBy('cnt', 'desc')
->get();

这将为您提供一组 Tag 对象。您会在它们的 cnt 属性中找到计数。

关于php - Laravel - belongsToMany 高效标签计数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34730191/

26 4 0