Eloquent: Complex Script - laravel

Good day!
can be possible to change this script to Eloquent Laravel
SELECT concat(firstname, " ",lastname) as fullname,q_title,answer FROM `user_pivot_survey_answer` as upsa
LEFT JOIN (SELECT id,q_title FROM survey_question) sq ON upsa.qid = sq.id
LEFT JOIN (SELECT id,firstname,lastname FROM user_survey_answer) usa ON upsa.sid = usa.id
I translate it already to Eloquent, however, I don't know if is working
$testquery = DB::table('user_pivot_survey_answer')
->leftJoin(DB::select('SELECT id,q_title FROM survey_question'),function($join)) {
$join->on('user_pivot_survey_answer.id', '=', 'survey_question.id');
})
->leftJoin(DB::select('SELECT id,firstname,lastname FROM user_survey_answer'),function($join){
$join->on('user_pivot_survey_answer.id', '=', 'user_survey_answer.id');
});
Thanks

Use this:
$testquery = DB::table('user_pivot_survey_answer as upsa')
->select(DB::raw('concat(firstname, " ", lastname) as fullname'), 'q_title', 'answer')
->leftJoin(DB::raw('(SELECT id,q_title FROM survey_question) sq'), 'upsa.qid', 'sq.id')
->leftJoin(DB::raw('(SELECT id,firstname,lastname FROM user_survey_answer) usa'), 'upsa.sid', 'usa.id');

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();

How to Convert this Query to Eloquent or Query Builder?

I have a query like this. How should I convert it into a eloquent or query builder
SELECT
x.MATERIAL_ID,
(SELECT TAPET_NAME FROM MA_TAPE_TYPE WHERE TAPET_CODE = x.MATERIAL_TYPE) as media_type,
(SELECT TAPEF_NAME FROM MA_TAPE_FORMAT WHERE TAPEF_CODE = x.MATERIAL_FORMAT) as media_format,
STOCK_MATERIAL_EPI.HOUSE_NO,
x.TXN_DATE,
STOCK_MATERIAL_EPI.PROGRAM_NAME,
CASE WHEN x.iden_flag = 'P' THEN STOCK_MATERIAL_EPI.epi_title WHEN x.iden_flag = 'C'
THEN STOCK_MATERIAL_EPI.prod_version_name WHEN x.iden_flag = 'M' THEN STOCK_MATERIAL_EPI.promo_name
END as episode_title,
PUR_EPISODE_HDR.EPI_NO,
(SELECT MAX (last_date) FROM run_master WHERE run_master.row_id_epi = PUR_EPISODE_HDR.row_id AND
run_master.run_aired = 'Y') as last_tx,
x.REMARKS,
x.LOCATION_ID as shelf_no,
stock_material_slag.remarks as short_list
FROM STOCK_MATERIAL x
LEFT JOIN STOCK_MATERIAL_EPI ON x.MATERIAL_ID = STOCK_MATERIAL_EPI.MATERIAL_ID
LEFT JOIN stock_material_slag ON x.MATERIAL_ID = stock_material_slag.MATERIAL_ID
LEFT JOIN PUR_EPISODE_HDR ON STOCK_MATERIAL_EPI.ROW_ID_EPI = PUR_EPISODE_HDR.ROW_ID
I'm confused as to how to convert them. Can someone help me.
I tried to write like this.
But it doesn't work,
$materials = DB::connection('oracle')
->table('STOCK_MATERIAL AS x')
->select('x.MATERIAL_ID',
DB::raw("(SELECT TAPET_NAME FROM MA_TAPE_TYPE WHERE TAPET_CODE = x.MATERIAL_TYPE) as MEDIA_TYPE"),
DB::raw("(SELECT TAPEF_NAME FROM MA_TAPE_FORMAT WHERE TAPEF_CODE = x.MATERIAL_FORMAT) as MEDIA_FORMAT"),
'x.TXN_DATE',
'y.HOUSE_NO', 'y.PROGRAM_NAME',
DB::raw("(CASE WHEN x.IDEN_FLAG = 'P' THEN z.EPI_TITLE WHEN x.IDEN_FLAG = 'C' THEN z.PROD_VERSION_NAME WHEN x.IDEN_FLAG = 'M' THEN z.PROMO_NAME END as EPISODE_TITLE)"),
'w.EPI_NO',
DB::raw("(SELECT MAX (LAST_DATE) FROM RUN_MASTER WHERE RUN_MASTER.ROW_ID_EPI = w.ROW_ID AND RUN_MASTER.RUN_AIRED = 'Y') as LAST_TX"),
'z.REMARKS',
'x.LOCATION_ID as SHELF_NO',
'z.REMARKS'
)
->leftJoin('STOCK_MATERIAL_EPI AS y', 'y.MATERIAL_ID', '=', 'x.MATERIAL_ID')
->leftJoin('STOCK_MATERIAL_SLAG AS z', 'z.MATERIAL_ID', '=', 'x.MATERIAL_ID')
->leftJoin('PUR_EPISODE_HDR AS w', 'w.ROW_ID', '=', 'y.ROW_ID_EPI')
What else do I write right?
You would need to define eloquent models and then use with(). Documentation can be found at the link below: https://laravel.com/docs/7.x/eloquent-relationships#constraining-eager-loads
example
StockMaterial::with([
'maTapeType' => function($query) {
$query->get('name')
})
])
For Query Builder you DB::raw and DB::leftJoin to create the same query.
DB::from('STOCK_MATERIAL')
->selectRaw([
'TAPET_NAME as media_type',
'CASE WHEN x.iden_flag = "P" THEN STOCK_MATERIAL_EPI.epi_title
WHEN x.iden_flag = "C" THEN STOCK_MATERIAL_EPI.prod_version_name
WHEN x.iden_flag = "M" THEN STOCK_MATERIAL_EPI.promo_name
END as episode_title',
])
->leftJoin('MA_TAPE_TYPE', 'TAPET_CODE', 'STOCK_MATERIAL.MATERIAL_TYPE')
https://laravel.com/docs/7.x/queries#raw-expressions
https://laravel.com/docs/7.x/queries#joins

how to retrieve different names from same table with different ids on join laravel

I need to get names from destinations table for each from_destination_id and to_destination_id
as fromDestinationName and toDestinationName
$bookingTransfersData = DB::table('transfers as t')
->select('t.periodStart as periodStart', 't.periodEnd as periodEnd','t.days','t.transfer_id','t.cost_round_trip',
't.cost_one_way','t.status','d.destination_id as destinationId','d.name as destinationName', 't.type',
'tf.name as officeName', 'ag.name as agencyName', 'u.name as userName', 'v.name as vehicleName')
->join('destinations as d', function ($join){
$join->on('t.from_destination_id','=','d.destination_id')
->orOn('t.to_destination_id','=','d.destination_id');
})->join('vehicles as v','t.vehicle_id','=','v.vehicle_id')
->join('transfer_offices as tf','t.office_id','=','tf.transfer_office_id')
->join('agencies as ag','t.forAgency_id','=','ag.agency_id')
->join('users as u','t.addedBy_user_id','=','u.id')
->get();
i want to get the names of each id after this results
$searchResults = $bookingTransfersData
->where('periodStart','between', $periodStart && $periodEnd)
->where('periodEnd','between', $periodStart && $periodEnd)
->where('destinationName','=',$from_destination_name && $to_destination_name)->where('type','like', $type);
like:
$fromDestinationName = $searchResults->pluck('from_destination_id','destinationName')
->where('from_destination_id','=','destinationId');
but $fromDestinationName return an empty collection
please help :)
I solved it by removing this join:
->join('destinations as d', function ($join){
$join->on('t.from_destination_id','=','d.destination_id')
->orOn('t.to_destination_id','=','d.destination_id');
})
and add for each destionation_id a join to retrive each name
and this will not work if I don't add for table name that i joined two times as to name it new name like
'destinations as d1' and 'destinations as d2'
$bookingTransfersData = DB::table('transfers as t')
->select('t.periodStart as periodStart', 't.periodEnd as periodEnd','t.days','t.transfer_id','t.cost_round_trip',
't.cost_one_way','t.status','d1.destination_id as fromDestinationId','d1.name as fromDestinationName', 't.type',
't.to_destination_id','tf.name as officeName', 'ag.name as agencyName', 'u.name as userName', 'v.name as vehicleName',
't.from_destination_id', 'd2.destination_id as toDestinationId','d2.name as toDestinationName')
->join('destinations as d1','t.from_destination_id','=','d1.destination_id')
->join('destinations as d2','t.to_destination_id','=','d2.destination_id')
->join('vehicles as v','t.vehicle_id','=','v.vehicle_id')
->join('transfer_offices as tf','t.office_id','=','tf.transfer_office_id')
->join('agencies as ag','t.forAgency_id','=','ag.agency_id')
->join('users as u','t.addedBy_user_id','=','u.id')->get();
the problem solved :)

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)'

codeigniter - this->db->get() returns empty result

I have a problem regarding codeigniters db->get(). I have functioning sql query, when i pass it to db "manually", i get result, but when i use codeigniter, i get empty result. Almost same query but with like instead of where works.
The SQL is:
SELECT se.Id, se.Name, se.Alias, sy.Name as System, os.Name as Os, ac.Name as Access, se.Description
FROM cdl_server se
INNER JOIN cdl_system sy on sy.Id = se.System
INNER JOIN cdl_os os on os.Id = se.Os
INNER JOIN cdl_access ac on ac.Id = se.Access
WHERE se.Id = 1
The code looks like this:
$this->db->select(
'se.Id, se.Name, se.Alias, ' .
'sy.Name as System, os.Name as Os, ac.Name as Access, ' .
'se.Description',
FALSE);
$this->db->from('cdl_server se');
$this->db->join('cdl_system sy', 'sy.Id = se.System' ,'inner', FALSE);
$this->db->join('cdl_os os', 'os.Id = se.Os' ,'inner', FALSE);
$this->db->join('cdl_access ac', 'ac.Id = se.Access' ,'inner', FALSE);
$this->db->where('se.Id', $id, FALSE);
$this->db->get();
edit:
I use it like:
$query = $this->db->get();
return $query->result();
When i var_dump the sql query before it is sent to the database, i get this:
string(264) "SELECT se.Id, se.Name, se.Alias, sy.Name as System, os.Name as Os, ac.Name as Access, se.Description FROM cdl_server se INNER JOIN cdl_system sy ON sy.Id = se.System INNER JOIN cdl_os os ON os.Id = se.Os INNER JOIN cdl_access ac ON ac.Id = se.Access WHERE se.Id =1"
But result is always empty, even though when i copy the above and try asking db directly, i get result i need.
Does anyone know what could be causing it?
If u want to get result you must use row() or result() function.
$this->db->get()->result();

Resources