mysql多次查询_mysql – 使用Eloquent的Laravel和多次计数查询

每当在模型类上调用静态方法时,它都会返回一个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);

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值