how to retrieve different names from same table with different ids on join laravel - 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 :)

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

Codeigniter query with alias and number as column

I would like to replace column name with numbers in codeigniter
It does work well with letters but not with numbers
$this->db->select ('Observation.id_observation as 1');
$this->db->from ( 'Observation' );
$this->db->join ( 'Enregistrement', 'Enregistrement.id_observation =
Observation.id_observation' , 'left' );
$this->db->where('Observation.id_parcelle', $id_parcelle);
$this->db->where('Observation.id_observateur', $user_id);
$this->db->where('Observation.date_observation >=', $date_start);
$this->db->where('Observation.date_observation <=', $date_end);
return $this->db->get()->result();
Try the following
$this->db->select ('Observation.id_observation as `1`');
This will generate query as
Select `observation` as `1`....
From the Docs
Identifiers may begin with a digit but unless quoted may not consist solely of digits.
You can set alias name as string so you need to give within single quotes otherwise you will get syntax error
$this->db->select ('Observation.id_observation as `1`',FALSE);
$this->db->from ( 'Observation' );
$this->db->join ( 'Enregistrement', 'Enregistrement.id_observation =
Observation.id_observation' , 'left' );
$this->db->where('Observation.id_parcelle', $id_parcelle);
$this->db->where('Observation.id_observateur', $user_id);
$this->db->where('Observation.date_observation >=', $date_start);
$this->db->where('Observation.date_observation <=', $date_end);
return $this->db->get()->result();
OR
$var = '1';
$this->db->select ('Observation.id_observation as `'.$var.'`',FALSE);
OR
$query=$this->db->query('SELECT Observation.id_observation as "1" FROM Observation LEFT JOIN Enregistrement ON Enregistrement.id_observation =
Observation.id_observation WHERE Observation.id_parcelle = '.$id_parcelle.' AND Observation.id_observateur = '.$user_id.' AND Observation.date_observation >= "'.$date_start.'" AND Observation.date_observation <= "'.$date_end.'" ');
return $query->result();
You can try this:
$this->db->select ("Observation.id_observation as '1'");
Hope It will work.
This is what i had to do in the controller ! I very don't like this solultion but it does work:
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT
Observation.id_observation as '0',
Observation.checkseries as '1'
FROM Observation
LEFT JOIN Enregistrement ON Enregistrement.id_observation = Observation.id_observation
WHERE
Observation.id_parcelle = '$parcellecultures->id_parcelle'
AND Observation.id_observateur = '$user'
AND Observation.date_observation >= '$date_start'
AND Observation.date_observation <= '$date_end'
";
//echo $sql;
$result = $conn->query($sql);
//print_r($result);exit;
$conn->close();
I still look for another solution ....

Eloquent: Complex Script

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

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

Laravel 5 where condition to get pass 30 days worth of records

I have a date column in the instances table with varchar datatype stored as d-m-Y. In my where condition I am trying to fetch records for just past 30 days only.
$backdate = Carbon::parse('-30 days')->toDateString();
$date30DaysBack = Carbon::parse($backdate)->format('d-m-Y');
$adverts = DB::table('adverts')
->where(DB::raw('STR_TO_DATE(instances.date,"%d-%m-%Y")'), '>=',$date30DaysBack)
The full query
$adverts = DB::table('adverts')
->select(DB::raw('(SELECT IF(ext = \'jpeg\', CONCAT(fullpath, \'_1.\', ext), (CONCAT(fullpath,\'.\',ext))) as fullpath FROM advertsstorage where uid_dir = adverts.ad_uid ORDER BY id ASC limit 1)as fullpath, adverts.*, domains.location,instances.date'))
->join('domains','adverts.domain', '=' ,'domains.domain')
->join('advertiser_domains','domains.id', '=' ,'advertiser_domains.domain_id')
->join('advertisers','advertiser_domains.advertiser_id', '=' ,'advertisers.u_id')
->join('instances','adverts.ad_uid','=','instances.ad_uid')
->join('urls','instances.u_id','=','urls.id')
->join('sites','urls.sites_id','=','sites.id')
->where('advertisers.u_id', '=',$advertiserID)
->where(DB::raw('STR_TO_DATE(instances.date,"%d-%m-%Y")'), '>=',Carbon::now()->subDays(30)->format('d-m-Y'))
->orderBy(DB::raw('STR_TO_DATE(instances.date,"%d-%m-%Y")'), 'DESC')
->get();
Did you try DATEDIFF method
$adverts = DB::table('adverts')
->select(DB::raw('(SELECT IF(ext = \'jpeg\', CONCAT(fullpath, \'_1.\', ext), (CONCAT(fullpath,\'.\',ext))) as fullpath FROM advertsstorage where uid_dir = adverts.ad_uid ORDER BY id ASC limit 1)as fullpath, adverts.*, domains.location,instances.date'))
->join('domains','adverts.domain', '=' ,'domains.domain')
->join('advertiser_domains','domains.id', '=' ,'advertiser_domains.domain_id')
->join('advertisers','advertiser_domains.advertiser_id', '=' ,'advertisers.u_id')
->join('instances','adverts.ad_uid','=','instances.ad_uid')
->join('urls','instances.u_id','=','urls.id')
->join('sites','urls.sites_id','=','sites.id')
->where('advertisers.u_id', '=',$advertiserID)
->where(DB::raw('DATEDIFF( now(), STR_TO_DATE(instances.date,"%d-%m-%Y") )'), '<=', 30)
->orderBy(DB::raw('STR_TO_DATE(instances.date,"%d-%m-%Y")'), 'DESC')
->get();
Have you checked out the Carbon docs?
You can use the subtraction modifier for this; Carbon::now()->subDays(30);.
Would look something like this in your code:
$adverts = DB::table('adverts')->where(DB::raw('STR_TO_DATE(instances.date,"%d-%m-%Y")'), '>=', Carbon::now()->subDays(30)->format('d-m-Y'))
Try this.
Carbon has subDays function by which you can get past 30 days data
$date30DaysBack= Carbon::now()->subDays(30)->format('d-m-Y');
$today = Carbon::now()->format('d-m-Y');
$adverts = DB::table('adverts')
->whereBetween(DB::raw('STR_TO_DATE(instances.date,"%d-%m-%Y")'),[$date30DaysBack,$today])->get()

Resources