Sum with SUM()

Asked

Viewed 1,025 times

2

Two days ago I’m banging head with a query in the database marrying tables and returning the sum of values, I can perform the query by the quiet Phpmyadmin.

Follows the query that works on Phpmyadmin:

Select sum(D.CargaHoraria) as CargaHorariaTotal, C.NomeCurso, C.CursoId, A.Imagem
             from Curso C
                  inner join Disciplina D on D.CursoId = C.CursoId
                  inner join Area A on A.AreaId = C.AreaId

             GROUP BY C.CursoId

It follows the same code on DB::select of Laravel and I can’t get back.

DB::select("        
          Select sum(D.CargaHoraria) as CargaHorariaTotal, C.NomeCurso, C.CursoId, A.Imagem
             from Curso C
                  inner join Disciplina D on D.CursoId = C.CursoId
                  inner join Area A on A.AreaId = C.AreaId

             GROUP BY C.CursoId
       ");

The intention and the following, I have Courses that each course has several disciplines, and each discipline has its hourly charge, I need to do the sum of the hourly charges of the disciplines to obtain the cargaHorariaTotal course.

But I’m not succeeding with the Laravel.

Controller

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Response;
use App\CursoModel;
use DB;


class CursosController extends Controller
{
    public function __construct(CursoModel $objeto)
    {
        //No Auth
        $this->curso = $objeto;
    }

    public function CursosPosGraduacao()
    {

        return view('Cursos/CursosPosGraduacao');
    }

    public function CursosFormacaoPedagogica()
    {
        return view('Cursos/CursosFormacaoPedagogica');
    }

    public function CursosSegundaLicenciatura()
    {
        return view('Cursos/CursosSegundaLicenciatura');
    }

    public function CursoDetalhe()
    {
        return view('Cursos/CursoDetalhe');
    }

    public function retornarTodosOsCursos()
    {
        $Query = DB::select(DB::raw("        
          Select sum(D.CargaHoraria) as CargaHorariaTotal, C.NomeCurso, C.CursoId, A.Imagem
             from Curso C
                  inner join Disciplina D on D.CursoId = C.CursoId
                  inner join Area A on A.AreaId = C.AreaId

             GROUP BY C.CursoId
       "));
        return $Query;
    }
}

Route

//Matricule
Route::group(['prefix'=>'api'], function(){
    Route::group(['prefix'=>'Curso'],function(){

        Route::get('retornarTodosOsCursos',['uses'=>'CursosController@retornarTodosOsCursos']);

    });
});

Cursomodel

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Input;
use Hash;
use Response;
use DB;

class CursoModel extends Model
{
    //
    protected $primaryKey = 'CursoId';
    protected $fillable = ['CursoId', 'AreaId', 'NomeCurso', 'DescricaoCurso', 'ImagemCurso', 'NumeroDoCurso', 'UsuarioId'];
    public $table = 'Curso';


    public function GetAllRepositorio()
    {
        return self::all();
    }

    public function PostRepositorio()
    {
        if (Auth::check()) { //verifica se tem usuario logado
            $data = new CursoModel();
            $data->fill(Input::all());

            if (is_null($data)) {
                return false;
            }

            //Confere se CursoId e maior que 0
            if ($data["CursoId"] > 0) {
                //Envia o registro para Atualizar ja que o mesmo tem CursoId
                $data = $this->AtualizaRegistro($data["CursoId"]);
                //Se salvar retorna true se não retorna falso
                return $data;
            }

            $TodosOsCursos = self::all();
            foreach ($TodosOsCursos as $key => $value) {
                if ($value['NumeroDoCurso'] == $data['NumeroDoCurso'] || $value['NomeCurso'] == $data['NomeCurso']) {
                    return false;
                }
            }

            $data['UsuarioId'] = Auth::user()->id;
            return $data->save();
        }
    }

    public function DeletarRepositorio($id)
    {
        $data = self::find($id);
        if (is_null($data)) {
            return false;
        }
        $data->delete();
        return true;
    }

    public function AtualizaRegistro($CursoId)
    {
        if (Auth::check()) { //verifica se tem usuario logado
            //Procura registro no banco pelo $id
            $data = self::find($CursoId);

            //Caso não encontrar registro no banco retorna falso, abortando a operação
            if (is_null($data)) {
                return false;
            }

            //Recebe todos os valores novos que chegaram
            $input = Input::all();

            //Atribui os valores novos no registro 'data' encontrados no banco
            $data->fill($input);

            //Atribui o usuario que executou a ultima ação no registro
            $data['UsuarioId'] = Auth::user()->id;

            //Salva os registros no banco e retorna se atalizou ou não
            return $data->save();


        }
    }

    public function RetornaListaDeCursoPorArea($AreaId){

        $listaDeCursoPorArea = DB::table('Curso')->where('AreaId', $AreaId)->get();
        return $listaDeCursoPorArea;
    }
}
  • If you put a dd('Teste') above the variable $Query and enters the LINK does not show 'Test' ?

2 answers

1

It is necessary to make a DB::raw or you can do using Eloquent. Maintenance is best in the latter case.

Fluent

DB::select(DB::raw("        
          Select sum(D.CargaHoraria) as CargaHorariaTotal, C.NomeCurso, C.CursoId, A.Imagem
             from Curso C
                  inner join Disciplina D on D.CursoId = C.CursoId
                  inner join Area A on A.AreaId = C.AreaId

             GROUP BY C.CursoId
       "));

Eloquent

$Query = Curso::join('Disciplina', 'Disciplina.CursoId', '=', 'Curso.CursoId')
              ->join('Area', 'Area.AreaId', '=', 'Curso.AreaId')
              ->selectRaw('SUM(Disciplina.CargaHoraria) AS CargaHorariaTotal, Curso.NomeCurso, Curso.CursoId, Area.Imagem')
              ->groupBy('Curso.CursoId')
              ->get();

All fields that will return in AJAX you have to put in variable $fillable.

protected $fillable = ['CursoId', 'AreaId', 'NomeCurso', 'DescricaoCurso', 'ImagemCurso', 'NumeroDoCurso', 'UsuarioId'];
  • Champ, I tried to do it this way but the same only works if I remove the parameters C.Nomecurso and A.Image thus staying so

  • Thus DB::select(DB::raw(" Select sum(D.Cargahoraria) as Cargahorariatotal, C.Cursoid from Curso C Inner Join Disciplina D on D.Cursoid = C.Cursoid Inner Join Area A on A.Areaid = C.Areaid GROUP BY C.Cursoid "));

  • Yes ... the field names are ok, so much so that with C.Cursoid it works cool.. but if I insert C.Nomenclature it doesn’t work.

  • I do a request by API so it returns me error 500 (Internal Server Error) - there is some way to get the error from Laravel and return?

  • Look, the link is right, but when it executes the query and generates an error, it stops and returns error 500, so that when I put the query that works, without all the parameters it works cool.

  • I put true, I’ll try to do with dd to see if return

  • Nothing, no return error

  • $Query = DB::select(DB::raw(" Select sum(D.Cargahoraria) as Cargahorariatotal, C.Cursoid from Curso C Inner Join Disciplina D on D.Cursoid = C.Cursoid Inner Join Area A on A.Areaid = C.Areaid GROUP BY C.Cursoid "));

  • Can you post your Controller and Route ? Click on the LINK edit below your question and put there to see.

  • THIS QUERY DOES NOT WORK $Query = DB::select(DB:::raw(" Select sum(D.Cargahoraria) as Cargahorariatotal, C.Course Name, C.Cursoid, A.Picture from Course C Inner Join Disciplina D on D.Cursoid = C.Cursoid Inner Join Area A on A.Areaid = C.Areaid GROUP BY C.Cursoid "));

Show 5 more comments

0


It could also be the following:

in config/database.php:

Change to this:

...
'strict'=>false
...

So that you do not default to GROUP in the query

  • I can do the sums of the Horaria Load of the separate disciplines, he error when adding some other field to the select..

  • Did you try it like I put it on top? Maybe you need to adjust the Models' names, but this is how I would do it, I think I got what you want. Make the sum of the hourly load of all disciplines belonging to a given course @T.Matoso

  • That’s just what I need, adjusted as you said above Foreign key but unsuccessfully!

  • Is there an error? Are the Models' names correct? @T.Matoso

  • @T.Matoso what appears if you do dd(Curso::find(1)->disciplinas); with this model I put on top? id=1 course has some dics?

  • I use API Laravel, so I can not return any error, I know that when the error is 500 (Internal Server Error) the models are correct

  • You know what you can do, open the console, go to the tab network, all the requests appear on the left, click on the first one that should be the url you requested, if you have in the . env DEBUG=TRUE, will appear the html that returns with the @T.Matoso error

  • Yes, I identified here by the network, but just give me a return 500(Internal Server Error) follows the return status with the error

  • Request URL:http://localhost:8000/api/Course/returnsOsCursos Request Method:GET Status Code:500 Internal Server Error Remote Address:[::1]:8000

  • Can you get it online? Try to access from the browser itself, write to the URL of the browser: http://localhost:8000/api/Course/returnTodosOsCursos to see what appears @T.Matoso

  • OF THAT MISTAKE! &#xA;&#xA;SQLSTATE[42000]: Syntax error or access violation: 1055 'coded362_gestorsite.C.NomeCurso' isn't in GROUP BY (SQL: &#xA;Select sum(D.CargaHoraria) as CargaHorariaTotal, C.NomeCurso, C.CursoId, A.Imagem&#xA;from Curso C&#xA;inner join Disciplina D on D.CursoId = C.CursoId&#xA;Inner Join Area A on A.Areaid = C.Areaid GROUP BY C.Cursoid ) ! ! !

  • Just do what I put on top and then into the way retornarTodosOsCursos, and makes dd(Curso::find(1)->disciplinas->sum('CargaHoraria')); see what appears @T.Matoso

  • Class 'Http Controllers Course App' not found

  • Because you have to create Model for the @T.Matoso course, you have no model for the course?

  • I’ll post my course model on top, dude Voce has facebook?

  • @T.Matoso, I edited on top the answer according to the name of your Model, adjust the name of the Model of the disciplines also

Show 11 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.