case when not working in laravel query joint script - laravel

$billing_review_data = DB::table('_bvARAccountsFull As cl')
->whereIn('DCLink',$clients)
->whereYear('ReadingDate', '=', $today->year)
->whereMonth('ReadingDate', '=', $today->month)
->select('cl.name','cl.account','cl.currencycode','cl.ulARJointSeparateBill','sa.ucSABillingAsset',DB::raw('sum(cmr.moncmr - cmr.monpmr) as monunit'),
DB::raw('sum(cmr.colcmr - cmr.colpmr) as colunit'),
DB::raw('sum(cmr.scncmr - cmr.scnpmr) as scnunit'),
DB::raw('sum(cmr.a3mcmr - cmr.a3mpmr) as a3munit'),
DB::raw('sum(cmr.a3ccmr - cmr.a3cpmr) as a3cunit'),
DB::raw('(CASE WHEN sa.ucSABillingAsset IS NULL THEN sa.ccode ELSE sa.ucSABillingAsset END) AS billingasset'),
DB::raw("(CASE WHEN sa.ucSABillingAsset IS Null THEN sa.cdescription ELSE 'Billed Asset' END) AS assetdesc")
)
->join('_smtblServiceAsset As sa', 'cl.DCLink', '=', 'sa.icustomerid')
->join('_cplmeterreading As cmr', 'sa.autoidx', '=', 'cmr.assetid')
->groupBy('cl.name','cl.account','cl.currencycode','cl.ulARJointSeparateBill','sa.ucSABillingAsset')
->get();
dd( $billing_review_data);
am using the CASE WHEN IS IN MY QUERY BUT IT DOESNT WORK AS INTENDED WHAT COULD BE THE ISSUE

Related

How to write raw query in Laravel?

There is a query:
SELECT ST_DistanceSpheroid(geometry(location), ST_GeomFromText('POINT(37.854289 55.685333)'), 'SPHEROID["WGS 84",6378137,298.257223563]')
FROM users
How to pass parameter 37.854289 55.685333?
Also I tried this:
$point = "37.854289 55.685333";
return DB::table('users')
->select(DB::raw('ST_DistanceSpheroid(geometry(location), ST_GeomFromText(\'POINT(?)\'), \'SPHEROID["WGS 84",6378137,298.257223563]\''), [$point])
->get();
I got this error:
"message": "stripos(): Argument #1 ($haystack) must be of type string, array given",
My attempt bases accepted question:
$lon = 37.857397;
$lat = 55.685333;
return DB::table('users')
->selectRaw(
"(ST_DistanceSpheroid(
geometry(location),
ST_GeomFromText('POINT(? ?)'),
'SPHEROID[?, ?, ?]'
)) as distance",
[$lon, $lat, 'WGS 84', 6378137, 298.257223563]
)->leftJoin('doctors', 'doctors.user_id', 'users.id')->orderBy('distance', 'ASC')->get();
I have got an error:
{
"message": "PDO: SQLSTATE[XX000]: Internal error: 7 ОШИБКА: SPHEROID parser - couldnt parse the spheroid\nLINE 4: 'SPHEROID[?, ?, ?]'\n ^ (SQL: select (ST_DistanceSpheroid(\n geometry(location),\n ST_GeomFromText('POINT(37.857397 55.685333)'),\n 'SPHEROID[WGS 84, 6378137, 298.257223563]'\n )) as distance from \"users\" left join \"doctors\" on \"doctors\".\"user_id\" = \"users\".\"id\" order by \"distance\" asc)"
}
The row query that works:
SELECT doctors.user_id, (ST_DistanceSpheroid(geometry(location), ST_GeomFromText('POINT(37.857397 55.690576)'), 'SPHEROID["WGS 84",6378137,298.257223563]')
) as distance FROM users INNER JOIN doctors ON doctors.user_id = users.id ORDER BY distance ASC
You almost got it. The [$point] parameter should be the second parameter of DB::raw($query, $bindings) but you added it as a second parameter to select().
// What you have
->select(DB::raw(...), [$point])
// correct syntax
->select(DB::raw(..., [$point]))
If you've got nothing else to put in your select clause, might as well use selectRaw(). It's the same as select(DB::raw()).
DB::table('users')
->selectRaw('ST_DistanceSpheroid(geometry(location), ST_GeomFromText(\'POINT(?)\'), \'SPHEROID["WGS 84",6378137,298.257223563]\')', [$point])
Personally, I'd write the query like this:
$query = DB::table('users')
->selectRaw(
"ST_DistanceSpheroid(
geometry(location),
ST_GeomFromText('POINT(? ?)'),
'SPHEROID[?, ?, ?]'
)",
[37.854289, 55.685333, 'WGS 84', 6378137, 298.257223563]
)
->get();

Count every records that exist on each program per college using Laravel

I have this query that produces all the College program.
$report = DB::table('college')
->leftJoin('program', 'program.college_id', '=', 'college.college_id')
->leftJoin('application', 'application.college_id', 'college.college_id')
->leftJoin('application_status', 'application_status.id', '=', 'application.status')
->select('college.college_name', 'program.program_name', 'program.program_id', 'program.track', 'application.acad_year', 'application.semester', 'application_status.name as name',
// DB::raw('SUM(application.application_no) as total'),
DB::raw('COUNT(program.college_id = '.$request->college_id.') as total'),
)
->where([
'application.acad_year' => $request->acad_year,
'application.semester' => $request->semester,
'college.college_id' => $request->college_id,
'application.status' => $request->status_id
])
->groupBy('program.program_id')
->get();
What I want is, I want to get all the "Applicants" each "Program" by Colleges. My problem is, the count of all applicants on each programs by colleges.

difference between 2 dates - illuminate manager laravel

I make a tv program schedule and I need to sort dates that are more than 600 seconds apart
But it don't work ;(
Anyone know how to do it?
Many thanks in advance to those who will help me.
$dateMin = Carbon::now('Europe/Paris')
->endOfDay()
->addDay()
->addHours(-4)
->timestamp;
$dateMax = Carbon::now('Europe/Paris')
->endOfDay()
->addDay()
->timestamp;
$datas = Capsule::table('channels')
->select('channels.number',
'channels.slug',
'channels.display-name',
'channels.icon',
'programs.start',
'programs.stop',
'programs.title',
'programs.img',
'programs.thumbnail',
'programs.desc'
)
->where([
['start', '>', $dateMin],
['stop', '>', $dateMin],
['start', '<', $dateMax],
])
->whereRaw('stop - start > 601')
->leftJoin('programs', 'channels.slug', '=', 'programs.slug')
->orderBy('number')
->orderBy('start')
->get();
return $datas->groupBy('display-name');
Without much context, the only thing I can think of is to try grouping the parameters in where clause
$datas = Capsule::table('channels')
->select('channels.number',
'channels.slug',
'channels.display-name',
'channels.icon',
'programs.start',
'programs.stop',
'programs.title',
'programs.img',
'programs.thumbnail',
'programs.desc'
)
->where(function($query) use($dateMin,$dateMax) {
$query->where([
['start', '>', $dateMin],
['stop', '>', $dateMin],
['start', '<', $dateMax],
])
->whereRaw('stop - start > 601')
})
->leftJoin('programs', 'channels.slug', '=', 'programs.slug')
->orderBy('number')
->orderBy('start')
->get();
If this doesn't work, try dumping the query sql for both, without parameter grouping (code in your question) and with parameter grouping (code above in my answer) and see the sql statement generated. You can get the query sql using toSql() in place of get().

One hour interval - Laravel

I'm trying to select all records based on date/time.
I have this timestamps in postgreSQL:
13/12/2020 11:00:00
14/12/2020 11:31:00
14/12/2020 12:30:00
14/12/2020 13:00:00
15/12/2020 02:00:00
I have a code in the controller getting all records:
$start_date = date('d/m/Y 00:00:00');
$end_date = date('d/m/Y 23:59:59');
if($request->start_date != '' && $request->end_date != '')
{
// if user fill dates
$dateScope = array($request->start_date, $request->end_date);
} else {
// default load page - today
$dateScope = array($start_date, $end_date);
};
$results = Tablemodel1::whereBetween('table1.recordtime', $dateScope)
->selectRaw('table1.recordtime','table2.info')
->orderBy('recordtime', 'ASC')
->get();
The goal is to select only records in every hour like this:
13/12/2020 11:00:00
14/12/2020 13:00:00
15/12/2020 02:00:00
I get error when use:
$results = Tablemodel1::whereBetween('table1.recordtime', $dateScope)
->selectRaw('extract(hour from table1.recordtime)','table2.info')
->orderBy('recordtime', 'ASC')
->get();
The error is:
Undefined index: recordtime
You could use LIKE to get the records with timestamps that have no minutes or seconds and if there's no other processing required.
$results = Tablemodel1::whereBetween('table1.recordtime', $dateScope)
->where('table1.recordtime','LIKE', '%:00:00%')
->selectRaw('table1.recordtime','table2.info')
->orderBy('recordtime', 'ASC')
->get();
Also, your query could probably work with this slight fix (AS column_name)
$results = Tablemodel1::whereBetween('table1.recordtime', $dateScope)
->selectRaw('extract(hour from table1.recordtime) AS recordtime','table2.info')
->orderBy('recordtime', 'ASC')
->get();
Please try something like this:
$result = Tablemodel1::select([
DB::raw('count(table2.info) as counted_info'),
DB::raw('DATE_FORMAT(table1.recordtime, "%H") hour'),
])
->whereBetween('table1.recordtime', $dateScope)
->groupBy('hour')
->orderBy('hour')
->get();
You should do the next steps:
Format date
Group by formatted date (Example: DATE_FORMAT(orders.created_at, "%b %d") day)
Sort (optional)
collect data
All possible formates described here:
enter link description here

Leading 0 in serach box throws error (Laravel Datatable)

I have used left to join multiple tables in my controller method. It returns data as desired but when I type into search box '0' it throws an error.
Using https://datatables.yajrabox.com/ this Laravel Datatable plugin
It only happen when single zero(0) is there in search box. '00' or 't0102' works fine.
only single '0' as search value throws an error.
Happens on the demo site to
https://datatables.yajrabox.com/eloquent/row-num
try to search for 0(zero) only and it will throw back you an error.
After spending couple of hours I came to the conclusion the it is because in MySql query LIKE %0% is not adding inverted commas('') around 0(zero)
It should be LIKE '%0%' instead LIKE %0%.
Code snippet of problem
Below is my Query Builder Code
$surveys = DB::table('surveys as su')
->leftJoin('assignments as a', 'su.assignment_id', '=', 'a.id')
->leftJoin('rounds as r', 'a.round_id', '=', 'r.id')
->leftJoin('projects as p', 'r.project_id', '=', 'p.id')
->leftJoin('sites as s', 'a.site_id', '=', 's.id')
->leftJoin('fieldreps as f', 'a.fieldrep_id', '=', 'f.id')
->leftJoin('chains as ch','p.chain_id','=','ch.id')
->leftJoin('clients as c','ch.client_id','=','c.id')
->leftJoin('surveys_templates as t', 'su.template_id', '=', 't.id')
->where(function ($query) {
$query->where('a.is_reported', '=', true)
->orWhere('a.is_partial', '=', true)
->orWhere('a.is_approved', '=', true);
})
//->where('su.service_code', '!=', '')
->select([
'a.id as assignment_id',
'a.fieldrep_id',
'a.deadline_date',
'a.is_reported',
'a.is_partial',
'a.is_approved',
'c.client_logo',
'p.id as project_id',
'p.project_name',
'r.id as round_id',
'r.round_name',
's.site_code',
's.site_name',
's.city',
's.state',
's.zipcode',
'su.id as survey_id',
'su.status',
'su.service_code',
't.template_name',
DB::raw("CONCAT(IFNULL( DATE_FORMAT(a.schedule_date,'%e/%c/%Y'), DATE_FORMAT(r.schedule_date,'%e/%c/%Y')), ' ' , IFNULL(a.start_time, r.start_time)) as assignment_scheduled"),
DB::raw("CONCAT(IFNULL( DATE_FORMAT(a.schedule_date,'%d %b %Y'), DATE_FORMAT(r.schedule_date,'%d %b %Y')), ' ' , IFNULL(a.start_time, r.start_time)) as assignment_scheduled_date"),
DB::raw("CONCAT(DATE_FORMAT(a.start_date,'%d %b %Y'),' ',a.start_time) as assignment_starts"),
DB::raw('CONCAT(f.first_name," ",f.last_name) as schedule_to'),
]);
Syntax error or access violation: 1583 Incorrect parameters in the call to native function 'LOWER' (SQL: select count(*) as aggregate from (select a.id as assignment_id, a.fieldrep_id, a.deadline_date, a.is_reported, a.is_partial, a.is_approved, c.client_logo, p.id as project_id, p.project_name, r.id as round_id, r.round_name, s.site_code, s.site_name, s.city, s.state, s.zipcode, su.id as survey_id, su.status, su.service_code, t.template_name, CONCAT(IFNULL( DATE_FORMAT(a.schedule_date,'%e/%c/%Y'), DATE_FORMAT(r.schedule_date,'%e/%c/%Y')), ' ' , IFNULL(a.start_time, r.start_time)) as assignment_scheduled, CONCAT(IFNULL( DATE_FORMAT(a.schedule_date,'%d %b %Y'), DATE_FORMAT(r.schedule_date,'%d %b %Y')), ' ' , IFNULL(a.start_time, r.start_time)) as assignment_scheduled_date, CONCAT(DATE_FORMAT(a.start_date,'%d %b %Y'),' ',a.start_time) as assignment_starts, CONCAT(f.first_name," ",f.last_name) as schedule_to from surveys as su left join assignments as a on su.assignment_id = a.id left join rounds as r on a.round_id = r.id left join projects as p on r.project_id = p.id left join sites as s on a.site_id = s.id left join fieldreps as f on a.fieldrep_id = f.id left join chains as ch on p.chain_id = ch.id left join clients as c on ch.client_id = c.id left join surveys_templates as t on su.template_id = t.id where (a.is_reported = 1 or a.is_partial = 1 or a.is_approved = 1) and (LOWER(s.site_code) LIKE %0% or LOWER(su.service_code) LIKE %0% or LOWER(p.project_name) LIKE %0% or LOWER(r.round_name) LIKE %0% or LOWER(s.city) LIKE %0% or LOWER(surveys as su.assignment_scheduled) LIKE %0% or LOWER(t.template_name) LIKE %0% or LOWER(surveys as su.schedule_to) LIKE %0%) order by lpad(s.site_code, 10, 0) desc) count_row_table)'

Resources