how to convert inner query in select to eloquent laravel 5.4 - php

I have a query like this..
select *,
case l.user_type
when '0' then
(select CONCAT(first_name,'',last_name) from users where id=l.user_id)
when '1' then
(select party_name from tbl_partys where id=l.user_id)
end as user_name
from tbl_leased_comm l
where l.user_id=$party and l.user_id=$user_id
order by l.updated_at desc
How to convert this query to laravel query
help me, anyone...

Yeah it works for me
as,
DB::table('tbl_leased_comm')
->select(["*",
DB::raw("case tbl_leased_comm.user_type when '0' then (select CONCAT(first_name,'',last_name) from users where id=tbl_leased_comm.user_id) when '1' then (select party_name from tbl_partys where id=tbl_leased_comm.user_id) end as user_name")])
->where('tbl_leased_comm.user_id','=',$party )
->where('tbl_leased_comm.user_id','=',$user_id)
->orderBy('tbl_leased_comm.updated_at', 'desc')
->get();
Thanks a lot..
reference link:Convert mysql query logic to Laravel query builder

Related

How to convert raw subquery into laravel query with query builder?

I have written a raw query which also contains subquery. I'm getting no idea that how to convert subquery in the laravel subquery with query builder.
Please someone convert this query. It will be very appreciable.
Query:
SELECT inventory.EmployeeID,
inventory.created_date AS OrderDate,
SUM(inventory.calculation) AS TotalPrice
FROM ( SELECT i.id AS ItemID,
o.id AS OrderID,
o.EmployeeID,
o.created_date,
(o.Quantity * i.price) AS calculation
FROM `stationary_orders` AS o
LEFT JOIN `stationary_items` AS i ON o.Stationary_ID = i.id
WHERE o.Store IN $storess
ORDER BY o.id DESC
LIMIT $Limit,10 ) AS inventory
GROUP BY inventory.EmployeeID
It took me a while to understand what's going on.
As I understood from your raw query, this is called a nested query.
You can use DB facade to make this query like this:
DB::select('inventory.EmployeeID, inventory.created_date AS OrderDate, SUM(inventory.calculation) AS TotalPrice')
->fromSub(function ($nestedQuery) use ($stores) {
$nesterQuery->select('i.id ...')->from('stationary_orders as o')
->leftJoin('stationary_items', 'o.Stationary_ID', '=', 'stationary_items.id')
->whereIn('o.Store', $stores)
...
}, 'inventory')
->groupBy('inventory.EmployeeID')->get()

Convert Raw SQL 'NOT' IN (too slow) to Laravel Eloquent

I have a running script using Raw SQL in Laravel 5.3 controller which I found it slow and not secure ( as Raw ). If there any way to make it more effecient and convert it to eloquent or Query Builder for Laravel ?
code as below & Thanks !
SELECT machine_code, machine_name
FROM factory_equipment
WHERE machine_code NOT IN
(
SELECT distinct(machine_code)
FROM echecklist_data
WHERE DATE_FORMAT(date, '%Y-%m-%d') = CURDATE()
)
AND type='production' ORDER BY machine_code ASC
You can make it more efficient using SQL. I would recommend NOT EXISTS:
SELECT fe.machine_code, fe.machine_name
FROM factory_equipment fe
WHERE NOT EXISTS (SELECT 1
FROM echecklist_data ed
WHERE ed.machine_code = fe.machine_code AND
ed.date >= CURDATE() AND
ed.date < CURDATE() + INTERVAL 1 DAY
) AND
fe.type = 'production'
ORDER BY fe.machine_code ASC;
I would further recommend indexes on: factory_equipment(type, machine_code, machine_name) and echecklist_data(machine_code, date).
You can speed up this query by making it into a LEFT JOIN and selecting only rows which have no match in the echecklist_data table:
SELECT fe.machine_code, fe.machine_name
FROM factory_equipment fe
LEFT JOIN echecklist_data ed ON ed.machine_code = fe.machine_code AND DATE_FORMAT(ed.date, '%Y-%m-%d') = CURDATE()
WHERE fe.type='production' AND ed.machine_code IS NULL
ORDER BY fe.machine_code ASC
Note that if your date column is a DATETIME type, then using DATE(ed.date) = CURDATE() will also be more efficient than DATE_FORMAT(ed.date, '%Y-%m-%d') = CURDATE().
I managed to get it working using laravel's query. Hope it helps others
DB::table('factory_equipment')
->select('factory_equipment.machine_code', 'factory_equipment.machine_name')
->leftjoin('echecklist_data', function ($leftjoin) {
$leftjoin->on('factory_equipment.machine_code', '=', 'echecklist_data.machine_code')
->Where( DB::raw("DATE_FORMAT(echecklist_data.date, '%Y-%m-%d')"), DB::raw("CURDATE()") );
})
->where('factory_equipment.type' , '=', 'production')
->whereNull('echecklist_data.machine_code')
->get();

phymyadmin add row number in query result

Hi i have this sql code i want to query in phpmyadmin
SELECT DISTINCT `unit`,`location` FROM `myasset` ORDER BY `unit` asc
It is possible to add custom number in my sql result
I tried something like below..its not working ..i received message row_number function does not exist
SELECT DISTINCT Row_Number(),`unit`,`location` FROM `myasset` ORDER BY `unit`
SELECT Row_Number() DISTINCT`unit`,`location` FROM `myasset` ORDER BY `unit`
First you have to set a value like
SET #rnum = 0;
then
SELECT #rnum:=#rnum+1 AS row_num, DISTINCT unit,location FROM myasset ORDER BY unit asc
Hope it will solve your issue.
Thanks
You could do
select #rownum:=#rownum+1 No,DISTINCT unit,location FROM myasset ORDER BY unit, (SELECT #rownum:=0);

how to count items on laravel query?

i need to count hours. this is my laravel eloquent:
$items = Item::ofType('type')->where('start_at','>=',Carbon::today())->groupBy(\DB::raw('HOUR(start_at)'))->count();
And this is show me results like 2/2/1
sql query of this:
SELECT
count(*)AS AGGREGATE
FROM
`items`
WHERE
`type` = 'type'
AND `start_at` >= '2015-10-15 00:00:00'
GROUP BY
HOUR(start_at)
And how to count 2/2/1 of this and get result = 3?
I need laravel eloquent without RAW.
EDIT:
SELECT COUNT(*) FROM (SELECT
count(*) AS AGGREGATE
FROM
`items`
WHERE
`type` = 'type'
AND `start_at` >= '2015-10-15 00:00:00'
GROUP BY
HOUR(start_at)) as count
how to write this in laravel eloquent?
you can use this code check laravel documentation on this link. http://laravel.com/docs/4.2/queries
Order By, Group By, And Having
$users = DB::table('items')
->orderBy('name', 'desc')
->groupBy('count')
->having('count', '>', 100)
->get();

Selecting most recent record for each user in codeigniter

i found this query which i believe is going to solve my problem :
SELECT MemberID, ContractID, StartDate, EndDate
FROM member_contracts
WHERE ContractId IN (
SELECT MAX(ContractId)
FROM member_contracts
GROUP BY MemberId
)
this query hass been given by #Mark Byers as an answer to another question.
how can i use this query in CodeIgniter especially the "Where_in" clause.
thanks
You can still use active record library to compile your subquery by using get_compiled_select()
$this->db->select('MAX(ContractId)')
->from('member_contracts')
->group_by('MemberId');
$subquery = $this->db->get_compiled_select();
$this->db->select('MemberID, ContractID, StartDate, EndDate')
->from('member_contracts ')
->where("ContractId IN($subquery)", NULL, FALSE)
->get()
->result();
Also you can rewrite your query with join instead of sub query to get latest record per group and also a compound index on MemberId,ContractId will be useful
SELECT m.MemberID, m.ContractID, m.StartDate, m.EndDate
FROM member_contracts m
JOIN (
SELECT MemberId,MAX(ContractId) ContractId
FROM member_contracts
GROUP BY MemberId
) mm
USING(MemberId,ContractId)
In CI, you can use $this->db->query("yourquery"); to execute a query. Try with
$query=$this->db->query("SELECT MemberID, ContractID, StartDate, EndDate
FROM member_contracts
WHERE ContractId IN (
SELECT MAX(ContractId)
FROM member_contracts
GROUP BY MemberId
)");

Categories