Laravel 在选择中选择计数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30781482/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel select count in select
提问by Jeffrey
I use laravel 4.2, I'have a table called pois who contain some poi (poi = point of interest), i'have a second table called stamps who contain user stamps.
我使用 laravel 4.2,我有一个名为 pois 的表,其中包含一些 poi(poi = 兴趣点),我有第二个表,名为stamps,其中包含用户图章。
So i want to have the 3 pois where user have the maximum amount of stamp. My problem is i dont know how to this using laravel queries. I got my result using sql request, but it'snt the good way to do this. here my sql request :
所以我想要用户拥有最大数量邮票的 3 泊。我的问题是我不知道如何使用 laravel 查询。我使用 sql 请求得到了结果,但这不是执行此操作的好方法。这是我的 sql 请求:
$pois = DB::select("SELECT *, (SELECT count(*) from stamps WHERE pois.id = stamps.poi_id) nbr_stamps FROM pois order by nbr_stamps DESC limit 3");
can you tell me how to do this with laravel queries ?
你能告诉我如何用 Laravel 查询做到这一点吗?
回答by Limon Monte
You should use selectRaw()
instead of select()
and separate other parts of query to related methods:
您应该使用selectRaw()
代替select()
并将查询的其他部分与相关方法分开:
$pois = DB::select(DB:raw("*, (SELECT count(*) from stamps WHERE pois.id = stamps.poi_id) nbr_stamps"))
->from('pois')
->orderBy('nbr_stamps', 'DESC')
->limit(3);
Read the Query Builder documentation.
阅读查询生成器文档。
回答by Jeffrey
@thanks to limonte for the documentation link, i found the right way to write to select raw, here the solutions :
@感谢 limonte 提供文档链接,我找到了正确的写入方式来选择原始数据,这里是解决方案:
$pois = DB::table('pois')
->select(DB::raw("*, (SELECT count(*) from stamps WHERE pois.id = stamps.poi_id) nbr_stamps"))
->orderBy('nbr_stamps', 'DESC')
->take(3)
->get();
have a nice day ;)
祝你今天过得愉快 ;)