Leading 0 in serach box throws error (Laravel Datatable) - laravel

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

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

This query works well in Mysql but in Postgres it is giving error

This query works fine when I was using Mysql, now that we've migrated to Postgres, it's giving an error. Where is the problem?
public function scopeClosestTo(\Illuminate\Database\Eloquent\Builder $query, array $coord = null)
{
if ($coord && isset($coord['longitude'], $coord['latitude'])) {
return $query->select([
'*',
'distance' => DB::table( 'offers as offers_temp' )->selectRaw(
'ST_Distance_Sphere(point(`longitude`, `latitude`), point(?, ?)) AS distance',
[$coord['longitude'], $coord['latitude']]
)->whereColumn('offers_temp.id', 'offers.id')
])
->withCount(['favoriteOffers'])
->where('published', '=', true)
->where('active', '=', true)
->whereNotNull('longitude')
->whereNotNull('latitude')
->whereDate('expires_at', '>', \Carbon\Carbon::now())
->orWhereNull('expires_at')
->orderBy('distance');
}
return $query;
}
Error:
"SQLSTATE[42601]: Syntax error: 7 ERROR: syntax error at or near ","\nLINE 1: ...ct , (select ST_Distance_Sphere(point(longitude, latitud...\n ^ (SQL: select *, (select ST_Distance_Sphere(point(longitude, latitude`), point(-43.3722344, -22.7867144)) AS distance from "offers" as "offers_temp" where "offers_temp"."id" = "offers"."id") as "distance", (select count() from "favorite_offers" where "offers"."id" = "favorite_offers"."offer_id" and "favorite_offers"."deleted_at" is null) as "favorite_offers_count" from "offers" where (("published" = 1 and "active" = 1 and "longitude" is not null and "latitude" is not null and "expires_at"::date > 2022-03-28 or "expires_at" is null) and "longitude" is not null and "latitude" is not null and exists (select * from "offer_categories" inner join "offers_offer_categories" on "offer_categories"."id" = "offers_offer_categories"."offer_category_id" where "offers"."id" = "offers_offer_categories"."offer_id" and "offers_offer_categories"."offer_category_id" in (1) and "offer_categories"."deleted_at" is null) and "to_companies" = 0 and "published" = 1 and "active" = 1 and "expires_at"::date > 2022-03-28 or "expires_at" is null) and "offers"."deleted_at" is null order by "distance" asc limit 15 offset 0)"
Your query uses backticks to escape column names, which works in MySQL. However, PostgreSQL uses double quotes to escape column names.
Change
point(`longitude`, `latitude`)
To
point("longitude", "latitude")
However, the words longitude and latitude are not reserved words in postgres, so there should be no reason you need to quote them.
See this article on the PostgreSQL wiki for more about moving from MySQL to PostgreSQL.

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

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

Doctrine QueryBuilder How to do that

This is in symfony.
How to do it better this work on one env on other doesn't don't know why
r. is Recruitment Entity which has onetomany relation to RecruitmentUsers
$this->createQueryBuilder('r')
->select('r')
->addSelect('(SELECT SUM(b.payedAmount) FROM APP\Entity\RecruitmentUsers b WHERE b.isActive = 1 and r.id = b.recruitment) as payedSum')
->addSelect('(SELECT SUM(c.declaredAmount) FROM APP\Entity\RecruitmentUsers c WHERE c.isActive = 1 and r.id = c.recruitment) as declaredSum')
->leftJoin('r.recruitmentUsers','u')
->groupBy('r.id')
->orderBy('r.id', 'DESC')
->getQuery()
->getResult()
In dev env everything works fine in prod i got this error:
Fatal error: Uncaught Doctrine\ORM\Query\QueryException: SELECT r, (SELECT SUM(b.payedAmount) FROM APP\Entity\RecruitmentUsers b WHERE b.isActive = 1 and r.id = b.recruitment) as payedSum, (SELECT SUM(c.declaredAmount) FROM APP\Entity\RecruitmentUsers c WHERE c.isActive = 1 and r.id = c.recruitment) as declaredSum FROM App\Entity\Recruitment r LEFT JOIN r.recruitmentUsers u GROUP BY r.id ORDER BY r.id DESC in /usr/home/eliteinvestments/domains/4eliteinvestments.pl/vendor/doctrine/orm/lib/Doctrine/ORM/Query/QueryException.php:43 Stack trace: #0 /usr/home/eliteinvestments/domains/4eliteinvestments.pl/vendor/doctrine/orm/lib/Doctrine/ORM/Query/Parser.php(487): Doctrine\ORM\Query\QueryException::dqlError('SELECT r, (SELE...') #1 /usr/home/eliteinvestments/domains/4eliteinvestments.pl/vendor/doctrine/orm/lib/Doctrine/ORM/Query/Parser.php(987): Doctrine\ORM\Query\Parser->semanticalError('line 0, col 42 ...', Array) #2 /usr/home/eliteinvestments/domains/4eliteinvestments.pl/vendor/doctrine/orm/lib/Doctrine/ORM/Query/Parser.php(1 in /usr/home/eliteinvestments/domains/4eliteinvestments.pl/templates/bundles/TwigBundle/Exception/error.html.twig on line 6
I done cache:clear, cache:warmup, doctrine:cache:clear-query, doctrine:cache:clear-result, doctrine:cache:clear-metadata
none of it works.
Any hints ?
I would try something like this. Not entirely sure what you want tho.
$this->createQueryBuilder('r')
->select('r.id, SUM(u.payedAmount), SUM(u.declaredAmount)')
->leftJoin('r.recruitmentUsers','u')
->where('u.isActive = 1')
->groupBy('r.id')
->orderBy('r.id', 'DESC')
->getQuery()
->getResult();

Resources