Php 查询逻辑:根据标记的计数和另一个参数对标记进行分组
我有以下情况: 桌子 “职位” 为简洁起见省略 “标签” “post_标记”透视表Php 查询逻辑:根据标记的计数和另一个参数对标记进行分组,php,laravel-4,Php,Laravel 4,我有以下情况: 桌子 “职位” 为简洁起见省略 “标签” “post_标记”透视表 'id', 'post_id', 'tag_id' 模型 Models\Post.php Models\Tag.php 控制器 $tags的输出示例 在我的模板中,我希望将数据分组如下: 男性 女性 请注意,顺序是从最高发生次数到最低发生次数。 因此,在本例中,我不仅需要访问标记的计数,还需要按种类属性male和female对它们进行分组 我需要执行什么样的查询才能获得所需的输出?不幸的是,我不太擅长
'id', 'post_id', 'tag_id'
模型
Models\Post.php
Models\Tag.php
控制器
$tags的输出示例
在我的模板中,我希望将数据分组如下:
男性
女性
请注意,顺序是从最高发生次数到最低发生次数。
因此,在本例中,我不仅需要访问标记的计数,还需要按种类属性male和female对它们进行分组
我需要执行什么样的查询才能获得所需的输出?不幸的是,我不太擅长创建MySQL语句。提前谢谢 类似的东西可能无法100%确定,因为没有测试,但请尝试一下:
$u = Posts::with(array('tags' => function($query) {
$query->select(DB::raw('count(name) as total'))
->groupBy('kind')
->orderBy('total', 'desc');
}))->whereSlug('hello-world')->first();
请让我知道结果
public function tags()
{
return $this->belongsToMany('Models\Tag');
}
public function posts()
{
return $this->belongsToMany('Models\Post');
}
$slug = 'hello-world';
$post = $this->posts->getFirstBy('slug', $slug);
$tags = $post->tags;
array (size=7)
0 =>
array (size=8)
'id' => int 1
'name' => string 'rough' (length=5)
'kind' => string 'male' (length=4)
1 =>
array (size=8)
'id' => int 2
'name' => string 'cosy' (length=4)
'kind' => string 'female' (length=6)
2 =>
array (size=8)
'id' => int 2
'name' => string 'cosy' (length=4)
'kind' => string 'female' (length=6)
3 =>
array (size=8)
'id' => int 2
'name' => string 'cosy' (length=4)
'kind' => string 'female' (length=6)
4 =>
array (size=8)
'id' => int 3
'name' => string 'sensual' (length=7)
'kind' => string 'female' (length=6)
5 =>
array (size=8)
'id' => int 4
'name' => string 'hard' (length=4)
'kind' => string 'male' (length=4)
6 =>
array (size=8)
'id' => int 1
'name' => string 'rough' (length=4)
'kind' => string 'male' (length=4)
- rough (2 occurances)
- hard (1 occurance)
- cosy (3 occurances)
- sensual (1 occurance)
$u = Posts::with(array('tags' => function($query) {
$query->select(DB::raw('count(name) as total'))
->groupBy('kind')
->orderBy('total', 'desc');
}))->whereSlug('hello-world')->first();