laravel for循环返回数据中的数据



我在数据库中有1个品牌和2个分支,我正在获取每个分支的销售数据。

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;

我的问题是:

  • 如果我将返回$netsalesdata放在for循环中,我只能获得第一个RAW(仅1个分支)
  • 如果我将其放在循环外,我将获得最后一行(仅第二个分支),而我的数据库有2个分支

将您的Netstellar更改为此(并将其保留在循环中):

$netsalesdata[$i]=[['BRANCHID' => $branches[$i]->BRANCHID, 'BRANCHNAME' =>branches[$i]->BRANCHNAME, 'MTDNETSALES' =>$mtdnetsales[0]->TOT, 'YTDNETSALES' =>$ytdnetsales[0]->TOT]];

并返回此:

return $netsalesdata[];
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]);
}

使用array_push函数附加新变量:

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;
}

最新更新