How to run a query string as SQL in laravel - laravel-5

I have a query in a variable and I want to run it :
$sql = "select id,
title,
parent_id
from (select * from categories
order by parent_cat_id, id) base,
(select #pv := '$category_id') tmp
where find_in_set(parent_cat_id, #pv) > 0
and #pv := concat(#pv, ',', id)";
How can run it as a query ?

I was able to run the query using the DB::select function:
$categories = DB::select($sql);
dd($categories);

Related

Which is the best efficient way to get many-to-many relation count in laravel?

I have students and subjects table in many-to-many relation (pivot table is student_subject).
Student Model
public function subjects()
{
return $this->belongsToMany(Subject::class, 'student_subject');
}
Subject Model
public function students()
{
return $this->belongsToMany(Student::class, 'student_subject');
}
Here I want the particular student subjects counts. I tried the below methods it's working fine but I want the best efficient way for this purpose.
1.
$student = Student::find($id);
$subject_count = $student->subjects()->count();
I checked the SQL query through laravel debuger it shows as below
select * from `students` where `students`.`id` = '10' limit 1
select count(*) as aggregate from `subjects` inner join `student_subject` on `subjects`.`id` = `student_subject`.`subject_id` where `student_subject`.`student_id` = 10 and `subjects`.`deleted_at` is null
$student = Student::withCount('subjects')->find($id);
$subject_count = $student->subjects_count;
I checked the SQL query through laravel debuger it shows as below
select `students`.*, (select count(*) from `subjects` inner join `student_subject` on `subjects`.`id` = `student_subject`.`subject_id` where `students`.`id` = `student_subject`.`student_id` and `subjects`.`deleted_at` is null) as `subjects_count` from `students` where `students`.`id` = '10' limit 1
$student = Student::find($id);
$subject_count = $student->loadCount('subjects')->subjects_count;
I checked the SQL query through laravel debuger it shows as below
select * from `students` where `students`.`id` = '10' limit 1
select `id`, (select count(*) from `subjects` inner join `student_subject` on `subjects`.`id` = `student_subject`.`subject_id` where `students`.`id` = `student_subject`.`student_id` and `subjects`.`deleted_at` is null) as `subjects_count` from `students` where `students`.`id` in (10)
$student = Student::find($id);
$subject_count = DB::table('student_subject')->where('student_id', $student->id)->count();
I checked the SQL query through laravel debuger it shows as below
select * from `students` where `students`.`id` = '10' limit 1
select count(*) as aggregate from `student_subject` where `student_id` = 10
According to the above ways which one is best and why? or if any different best way also there?
Doing relation()->count() is probably faster.
But if all you need is the count, withCount() should be better in terms of memory consumption.

Error request when I defined the column name

SQL :
select distinct b.nom, b.moyenne_pond
from previ.rdt_usine b
join previ.rdt r on (r.id_us=b.id_us)
where st_intersects(st_transform(st_setsrid(st_makepoint(55.40513629386126, -21.23713970920021), 4326), 32740),b.geom)
and r.annee=2018;
PHP :
$query = 'select distinct "b.nom", "b.moyenne_pond"
from "previ"."'.$name_table.'" b
join "previ"."rdt" r on (r.id_us=b.id_us)
where st_intersects(st_transform(st_setsrid(st_makepoint(?, ?), 4326), 32740), b.geom)
and r.annee=?';
$data = $db->select($query, $coord);
//$coord is an array of data
When I tried to use my request I have a this : column "b.nom" doesn't exist, but when I tried the query in pgAdmin the query is successfull, and you could see that the queries are exactly the same
Remove double quotes and add back tick
$query = 'select distinct `b.nom`, `b.moyenne_pond`
from `previ`.`$name_table` as b
join `previ`.`rdt` as r on (r.id_us=b.id_us)
where st_intersects(st_transform(st_setsrid(st_makepoint(?, ?), 4326), 32740), b.geom)
and r.annee=?';

How to use SQL raw query in Laravel

SQL table:
SELECT id,
account_name,
parent_id
FROM
(SELECT id,
account_name,
parent_id,
CASE
WHEN id = 1 THEN #idlist := CONCAT(id)
WHEN FIND_IN_SET(parent_id, #idlist) THEN #idlist := CONCAT(#idlist, ',', id)
END AS checkId
FROM chart_of_account
ORDER BY id ASC) AS T
WHERE checkId IS NOT NULL
When I run this query in MySQL it works fine and the result is fetched perfectly, but when I run it in Laravel like this:
$accountId = DB::select('SELECT id,account_name,parent_id FROM
(SELECT id,account_name,parent_id,
CASE WHEN id = '.$account_id.' THEN #idlist := CONCAT(id)
WHEN FIND_IN_SET(parent_id,#idlist) THEN #idlist := CONCAT(#idlist,', ',id)
END as checkId
FROM chart_of_account
ORDER BY id ASC) as T
WHERE checkId IS NOT NULL');
it gives an error.
Argument 1 passed to Illuminate\\Database\\Connection::prepareBindings() must be of the type array, string given,
Try this:
$query = 'YOUR_QUERY_THE_BIG_ONE:)';
$result = DB::select($query,[]);
dd($result);
Optionally, you can use ? sign in your query wherever you are using user inputs to prevent mySQL injection issue and then provide their value in second parameter array of select function. One example would be:
$inputUserEmail = $request->input('email');
$query = 'SELECT * FROM users WHERE email=?';
$result = DB::select($query,[$inputUserEmail]);
dd($result);
I hope it gives you an idea

laravel query builder from normal query

DB::select(DB::raw( 'SELECT a.bill_no, a.account_id, a.bill_date, a.amount_paid,
b.transaction_code,b.amount from bill_det a left join
(select bill_no, transaction_code, sum(amount) as amount from payment_transactions
where status = "success" group by bill_no ) b
on a.bill_no = b.bill_no where a.amount_paid != b.amount order by b.bill_no'));
this is normal query.change into laravel query?.
i tried.
$bill=DB::table('bill_det')->leftJoin('payment_transactions', 'bill_det.bill_no', '=', 'payment_transactions.bill_no')
->select('bill_det.bill_no','bill_det.account_id','bill_det.bill_date','bill_det.amount_paid',
'payment_transactions.transaction_code',DB::raw('sum(payment_transactions.amount) as amount'))
->where('payment_transactions.status','=','success')
->where('sum(payment_transactions.amount)','!=',DB::raw('bill_det.amount_paid'))
->groupBy('bill_det.bill_no')
->orderBy('bill_det.bill_no','desc');
i can't compare -> where('sum(payment_transactions.amount)','!=',DB::raw('bill_det.amount_paid'))
i used like this ->whereRaw('bill_det.amount_paid != sum(payment_transactions.amount)')
{"error":{"type":"Illuminate\Database\QueryException","message":"SQLSTATE[HY000]: General error: 1111 Invalid use of group function (SQL: select count(*) as aggregate from (select '1' as row_count from bill_det left join payment_transactions on bill_det.bill_no = payment_transactions.bill_no where payment_transactions.status = success and bill_det.amount_paid != sum(payment_transactions.amount) group by bill_det.bill_no order by bill_det.bill_no desc) count_row_table)"
DB::select(DB::raw( 'SELECT a.bill_no, a.account_id, a.bill_date, a.amount_paid,
b.transaction_code,b.amount from bill_det a left join
(select bill_no, transaction_code, sum(amount) as amount from payment_transactions
where status = "success" group by bill_no ) b
on a.bill_no = b.bill_no where a.amount_paid != b.amount order by b.bill_no'));
After converting this to laravel Query::
$query = \Illuminate\Support\Facades\DB::table('bill_det')
->select('a.bill_no', 'a.account_id', 'a.bill_date', 'a.amount_paid', 'b.transaction_code', 'b.amount')
->leftJoin(DB::raw('(select bill_no, transaction_code, sum(amount) as amount from payment_transactions
where status = "success" group by bill_no) b'), function($join) {
$join->on('a.bill_no', '=', 'b.bill_no');
})
->where('a.amount_paid','<>', 'b.amount')
->orderBy('b.bill_no')
->get();
In case you want to know how to use raw expression inside where then use this:
$query->whereRaw(DB::raw('(your expression!!)'));

Using variable in Oracle Connection Sql Query

I am trying to use variable in a SQL query but failed. What it the way to do this ?
var SicilNumvber = SessionCurrentUser.EMPNO;
string query = "select * from crm_visible_v where ownerid in (select sicilno from personel.pkim_kutlama#netdb_1.europe.nortel.com where cikis_tarihi is null start with sicilno = :SicilNumvber connect by prior sicilno = amir)";
Regards
Please concatenate the fixed string with the variable part as I have done below
string query := 'select * from crm_visible_v where ownerid in (select sicilno
from personel.pkim_kutlama#netdb_1.europe.nortel.com where cikis_tarihi is null
start with sicilno ='||SicilNumvber||' connect by prior sicilno = ''''amir'';
The success query is as below:
Thanks for your helps;
string query = "select * from crm_visible_v where ownerid in (select sicilno from personel.pkim_kutlama#netdb_1.europe.nortel.com where cikis_tarihi is null start with sicilno ='"+SicilNumvber+"' connect by prior sicilno = amir)";

Resources