mysql – 使用Eloquent的Laravel和多次计数查询
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了mysql – 使用Eloquent的Laravel和多次计数查询,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2269字,纯文字阅读大概需要4分钟。
内容图文
![mysql – 使用Eloquent的Laravel和多次计数查询](/upload/InfoBanner/zyjiaocheng/892/f349b4cade2f4daa8651b9237fb4a6ac.jpg)
我正在尝试优化我的代码,其中我在过去七天内生成统计数据.
目前我正在使用雄辩的和查询每天记录数据的计数,这使我在一个循环内进行7个单独的查询.
例:
// loop for number of days
for($i = 0; $i < $days; $i++){
// some logic to set comparitive unix times
$oldest = $newest - $dayDuration;
// count number of objects between oldest time and newest time
$counts[$i] = Object::where('objecttime','>',$oldest)
->where('objecttime','<',$newest)->count();
// more logic to set comparitive unix times
$newest = $newest - $dayDuration;
}
我知道可以使用类似于here所述的语法在sql中对查询进行分组;我想知道的是,是否可以使用Laravel中的雄辩/流利来做同样的事情,或者只能使用原始查询来做到这一点?
编辑:我不知道是否需要澄清,但这是一个Laravel 3问题.
解决方法:
每当在模型类上调用静态方法时,它都会返回一个Fluent查询,如DB :: table(‘yourmodeltable’) – >方法.如果你牢记这一点,你很快就会意识到可以用Eloquent模型进行任何查询.
现在,要实现更高的性能,可以使用SQL DATE()功能.我的下面的例子是未经测试的,请随意纠正.
// tomorrow -1 week returns tomorrow's 00:00:00 minus 7 days
// you may want to come up with your own date tho
$date = new DateTime('tomorrow -1 week');
// DATE(objecttime) turns it into a 'YYYY-MM-DD' string
// records are then grouped by that string
$days = Object::where('objecttime', '>', $date)
->group_by('date')
->order_by('date', 'DESC') // or ASC
->get(array(
DB::raw('DATE(`objecttime`) AS `date`'),
DB::raw('COUNT(*) as `count`')
));
foreach ($days as $day) {
print($day->date . ' - '. $day->count);
}
这应该打印如下:
2013-03-09 - 13
2013-03-10 - 30
2013-03-11 - 93
2013-03-12 - 69
2013-03-13 - 131
2013-03-14 - 185
2013-03-15 - 69
编辑:
上面建议的方法返回Eloquent Model的实例,这看起来很奇怪,特别是如果你var_dump($days).您也可以使用Fluent的list()方法来实现相同的功能.
$date = new DateTime('tomorrow -1 week');
// lists() does not accept raw queries,
// so you have to specify the SELECT clause
$days = Object::select(array(
DB::raw('DATE(`objecttime`) as `date`'),
DB::raw('COUNT(*) as `count`')
))
->where('created_at', '>', $date)
->group_by('date')
->order_by('date', 'DESC') // or ASC
->lists('count', 'date');
// Notice lists returns an associative array with its second and
// optional param as the key, and the first param as the value
foreach ($days as $date => $count) {
print($date . ' - ' . $count);
}
内容总结
以上是互联网集市为您收集整理的mysql – 使用Eloquent的Laravel和多次计数查询全部内容,希望文章能够帮你解决mysql – 使用Eloquent的Laravel和多次计数查询所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。