2014-09-23 31 views
5

साथ क्वेरी बिल्डर का उपयोग कैसे करें कैसे होगा मैं Laravel में क्वेरी बिल्डर का उपयोग निम्न SQL विवरण उत्पन्न करने के लिए:राशि() स्तंभ एवं GroupBy

SELECT costType, sum(amountCost) AS amountCost 
FROM `itemcosts` 
WHERE itemid=2 
GROUP BY costType 

मैं कई बातें की कोशिश की है, लेकिन मैं नहीं मिल सकता है sum() कॉलम एक नाम के साथ काम करने के लिए।

मेरे नवीनतम कोड:

$query = \DB::table('itemcosts'); 
$query->select(array('itemcosts.costType')); 
$query->sum('itemcosts.amountCost'); 
$query->where('itemcosts.itemid', $id); 
$query->groupBy('itemcosts.costType'); 
return $query->get(); 

उत्तर

10

groupBy और समेकित फ़ंक्शन (sum/count आदि) का उपयोग करना मतलब नहीं है।

क्वेरी बिल्डर के कुल मिलाकर एकल परिणाम लौटते हैं।

कहा, तो आप इस के लिए चयन raw हैं:

return \DB::table('itemcosts') 
    ->selectRaw('costType, sum(amountCost) as sum') 
    ->where('itemid', $id) 
    ->groupBy('costType') 
    ->lists('sum', 'costType'); 

का उपयोग get के बजाय lists यहाँ और अधिक उपयुक्त है, तो वह ऐसा सरणी वापस आ जाएगी:

[ 
'costType1' => 'sumForCostType1', 
'costType2' => 'sumForCostType2', 
... 
] 

get के साथ आप के लिए होता है :

[ 
stdObject => { 
    $costType => 'type1', 
    $sum => 'value1' 
}, 
... 
] 
संबंधित मुद्दे