2017-02-21 9 views
0

jQuery datatables 플러그인을 사용하고 볼 수있는 것처럼 별도로 foreach 루프를 사용하여 valores_receber (values_to_receive) 열을 추가하고 있습니다. 다음 코드에서.Laravel의 Eloquent를 사용하여 두 개의 다른 테이블에서 두 개의 열 값을 합하는 방법

public function anyDataReceber() { 

$clientes = Partner::whereHas('faturamentos', function($q){ 
     $q->where('status', '<>', 'CANCELADO'); 
    }) 
    ->orWhereHas('faturamentosLivres', function ($q) { 
     $q->where('status','<>','CANCELADO'); 
    }) 
    ->with('faturamentos') 
    ->with('faturamentosLivres'); 

return Datatables::of($clientes) 
    ->addColumn('valores_receber', function ($clientes) { 
     $total = 0; 
     foreach($clientes->faturamentos as $fatura1) { 
      if ($fatura1->status != 'CANCELADO') $total += $fatura1->total_usd - $fatura1->valor_pago; 
     } 
     foreach($clientes->faturamentosLivres as $fatura2) { 
      if ($fatura2->status != 'CANCELADO') $total += $fatura2->total_usd - $fatura2->valor_pago; 
     } 
     return number_format($total,2,',','.'); 
    }) 
    ->addColumn('action', function ($clientes) { 
     $actions = ''; 
     $actions = '<a href="/admin/financeiro-matriz/contas-receber/'.$clientes->id.'" class="btn btn-xs btn-primary"><i class="fa fa-eye"></i> Visualizar</a>'; 
     return $actions; 
    }) 
    ->make(true); 

}

여기서 문제는 바로이 열이 웅변의 결과 쿼리에 존재하지 않기 때문에 데이터 테이블은 열 valores_receber을 주문할 수 없다는 것입니다.

mySQL에서 SUM() 함수에 대해 조사했지만 Eloquent와 테이블 관계를 사용하여 솔루션을 만들 수 없습니다.

올바른 경로에 있어야하지만 대신 일반 SQL을 사용하고 있으며 조사한 결과 일종의 조인 또는 통합 문이 필요하지만 그 방법을 수행하는 방법은 무엇입니까?

  • How to sum data of two different columns of two different tables?
  • How to calculate sum of two columns from two different tables without where clause?
    • 는 그래서 데이터 테이블은 열 valores_receber를 주문 할 수 있도록, 나는 웅변 문 어떤 종류의 결과에 표시하기 위해 해당 열이 필요합니다.

      내가 달성하기 위해 시도하고 있습니다 :

      • 그 테이블 faturamentos 및 faturamentos_livres (송장 및 free_invoices)
      • 해당 테이블 모두에 존재 total_usd 컬럼의 값을 요약 설득력을 사용하여 쿼리를 만들 CANCELADO (취소됨)가 아닌 값이어야하는 상태 열에 의해 제한되어야합니다. 이 상태 열은 ENUM 유형을

      편집이다 : 원시() @ d1c1pl3에 의해 제안하지만 난 여전히 설득력을 사용하여 우아한 해결책을 알고 싶은대로 : 나는 DB 사용하고. 다음은 원시 쿼리를 사용하여 작품 내 추한 시도이며이 대답을 기반으로합니다 https://stackoverflow.com/a/7432219/2465086

      public function anyDataReceber() { 
      
      // 1 - getting all IDs of clients that have faturamentos or faturamentosLivres 
      
          $clientes = Partner::whereHas('faturamentos', function($q){ 
            $q->where('status', '<>', 'CANCELADO'); 
           }) 
           ->orWhereHas('faturamentosLivres', function ($q) { 
            $q->where('status','<>','CANCELADO'); 
           }) 
           ->with('faturamentos') 
           ->with('faturamentosLivres') 
           ->pluck('id') 
           ->toArray(); 
      
      // 2 - Converting to string for use in the query 
      
          $ids = implode(',',$clientes); 
      
      // 3 - the ugly query that I want to do using Eloquent. It filters by the status and filters by clients´ ids returned before. It is not appealing either because it uses subselects and a join 
      
          $result = DB::select(DB::raw(
             'SELECT partners.client, cliente_id, (SUM(t.total_usd) - SUM(t.valor_pago)) AS valores_receber 
      FROM (SELECT cliente_id, total_usd, valor_pago FROM faturamentos WHERE status <> "CANCELADO" AND cliente_id IN ('.$ids.') 
           UNION ALL 
           SELECT cliente_id, total_usd, valor_pago FROM faturamentos_livres WHERE status <> "CANCELADO" AND cliente_id IN ('.$ids.')) t 
      JOIN partners ON partners.id= cliente_id 
      GROUP BY cliente_id' 
             )); 
      
      // 4 - converting to Collection because the Datatables class expects it 
      
          $result = collect($result); 
      
      // 5 - The return is the only part that is easy to read and feels like it is in the right track 
      
          return Datatables::of($result) 
           ->editColumn('valores_receber', function ($result) { 
            return number_format($result->valores_receber,2,',','.'); 
           }) 
           ->addColumn('action', function ($result) { 
            $actions = ''; 
            $actions = '<a href="/admin/financeiro-matriz/contas-receber/'.$result->cliente_id.'" class="btn btn-xs btn-primary"><i class="fa fa-eye"></i> Visualizar</a>'; 
            return $actions; 
           }) 
           ->make(true); 
      } 
      

    답변

    관련 문제