jeudi 18 avril 2019

How to convert the sql query into laravel query builder?

I had a table with name, negeri and year of start service and end service.I want to get the number of years a person served in a state:

  ID | Name     | State   |   yearstart     |    yearend
  -----------------------------------------------------------
  1  | Tom      | Kedah   |      2001       |      2002
  1  | Tom      | Kedah   |      2003       |      2007
  2  | Anne     | Melaka  |      2008       |      2012
  2  | Anne     | Melaka  |      2013       |      2018
  3  | Bill     | KL      |      2000       |      2001

I had ask someone how to make sql statement for querying the information. This is the sql statement which works like this fidle http://sqlfiddle.com/#!9/9029438/4:

  select m.id,m.name,sum(m.duration) from (select ID,Name,yearend-yearstart 
  as duration from Table1)m group by  m.id,m.name;

I have tried with the following code. It is quite lengthy as it is searhcing function using if statement:

  $query = DB::table('itemregistrations')
                ->join('sections', 'itemregistrations.SectionID', '=', 'sections.SectionID')
                ->join('categories', 'itemregistrations.CategoryID', '=', 'categories.CategoryID')
                ->join('operasi', 'itemregistrations.OperasiID', '=', 'operasi.OperasiID')
                ->join('negeri', 'itemregistrations.NegeriID', '=', 'negeri.NegeriID')
                ->join('gred', 'itemregistrations.GredID', '=', 'gred.GredID')
                ->where('itemregistrations.statusProID', '=', 1)
                ->select('itemregistrations.name','sections.sectionname', 'categories.categoryname', 'operasi.operasiname', 'itemregistrations.Nobadan', 'itemregistrations.lahir_yy', 'itemregistrations.pdrm_yy', 'gred.namagred', 'itemregistrations.itemRegistrationID');

  if(request('tempoh_negeri')) {

     $query->select(DB::raw("(SELECT itemregistrationpangkat.ItemRegistrationID, itemregistrationpangkat.yeartamatkhidmat - itemregistrationpangkat.yearmulakhidmat as duration from itemregistrationpangkat)m"))
                  ->groupBy('m.ItemRegistrationID');

        }

The result is sent in json format to be displayed using ajax. It shows error 500 as the query is not working as expected.

What need to be improved the above code?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire