2013-03-15 54 views
3

我想優化我的代碼,其中我在過去七天生成統計信息。Laravel和使用雄辯的多重計數查詢

目前我正在使用口才&查詢每天的記錄數據的計數,這使我在一個循環內進行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; 
} 

我知道在SQL一個罐組查詢中使用類似的語法描述here;我想知道的是,如果能夠在Laravel中使用雄辯/流利來做同樣的事情,還是隻能使用原始查詢來做到這一點?

編輯:我不知道我是否需要澄清,但這是一個Laravel 3的問題。

回答

5

無論何時在您的模型類上調用靜態方法,它都將返回一個Fluent查詢,如DB::table('yourmodeltable')->method。如果你牢記這一點,你很快就會意識到可以用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 

編輯:

建議的方法上面洋洋灑灑模型的收益情況可能看起來怪異,特別是如果你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); 
} 
+0

感謝您的回覆,讓我給一個bash並回報。 – twaambo 2013-03-15 18:19:05

+0

我用最後使用的查詢更新了答案。再次感謝Vinícius。 – twaambo 2013-03-22 09:00:11

+0

group_by()和order_by()對我不起作用。我不得不使用groupBy()和orderBy()。 – 2014-10-03 15:11:24