Reputation: 269
I have 1 brand and 2 branches in my database, I'm getting the sales data for each branch.
public function getCurrentSales($brandid){
$branches = DB::table('gc_branch')->where('BRAND_ID', $brandid)
->select('BRANCHID', 'BRANCHNAME')
->get();
for ($i=0; $i<count($branches);$i++){
$mtdnetsales= DB::table('st_sales')
//query
->select(DB::raw('sum(AMOUNT) as TOT')->get();
$ytdnetsales= DB::table('st_sales')
//query
->select(DB::raw('sum(AMOUNT) as TOT')->get();
$netsalesdata=[['BRANCHID' => $branches[$i]->BRANCHID, 'BRANCHNAME' =>branches[$i]->BRANCHNAME, 'MTDNETSALES' =>$mtdnetsales[0]->TOT, 'YTDNETSALES' =>$ytdnetsales[0]->TOT]];
}//end for
return $netsalesdata;
My problem is :
$netsalesdata
in the for loop, I get the first raw only (1 branch only)Upvotes: 0
Views: 1054
Reputation: 46
Use array_push function to append new variables:
public function getCurrentSales($brandid){
$netsalesdata= [];
$branches = DB::table('gc_branch')->where('BRAND_ID', $brandid)
->select('BRANCHID', 'BRANCHNAME')
->get();
for ($i=0; $i<count($branches);$i++){
$mtdnetsales= DB::table('st_sales')
//query
->select(DB::raw('sum(AMOUNT) as TOT')->get();
$ytdnetsales= DB::table('st_sales')
//query
->select(DB::raw('sum(AMOUNT) as TOT')->get();
array_push($netsalesdata, ['BRANCHID' => $branches[$i]->BRANCHID, 'BRANCHNAME' =>branches[$i]->BRANCHNAME, 'MTDNETSALES' =>$mtdnetsales[0]->TOT, 'YTDNETSALES' =>$ytdnetsales[0]->TOT]);
}//end for
return $netsalesdata;
}
Upvotes: 0
Reputation: 2179
Change your netstellar to this (and keep it inside of for loop) :
$netsalesdata[$i]=[['BRANCHID' => $branches[$i]->BRANCHID, 'BRANCHNAME' =>branches[$i]->BRANCHNAME, 'MTDNETSALES' =>$mtdnetsales[0]->TOT, 'YTDNETSALES' =>$ytdnetsales[0]->TOT]];
and return this :
return $netsalesdata[];
Upvotes: 1
Reputation: 2943
public function getCurrentSales($brandid) {
$branches = DB::table('gc_branch')->where('BRAND_ID', $brandid)
->select('BRANCHID', 'BRANCHNAME')->get();
for ($i=0; $i<count($branches);$i++){
$mtdnetsales= DB::table('st_sales')
->select(DB::raw('sum(AMOUNT) as TOT')->get();
$ytdnetsales= DB::table('st_sales')
->select(DB::raw('sum(AMOUNT) as TOT')->get();
$netsalesdata[] =[
'BRANCHID' => $branches[$i]->BRANCHID,
'BRANCHNAME' =>branches[$i]->BRANCHNAME,
'MTDNETSALES' =>$mtdnetsales[0]->TOT,
'YTDNETSALES' =>$ytdnetsales[0]->TOT];
}//end for
// get size of the array
$records = count($netsalesdata);
// To get last record
print_r($netsalesdata[$records -1]);
}
Upvotes: 0