Laravel - How to Convert MySQL query to Laravel Eloquent - laravel

I have MySQL query I want to convert to Laravel Eloquent
I have written the query in MySQL
SELECT a.transaction_number a.date, a.item_number, b.desc, a.variant_code, sum(a.quantity) AS quantity, a.cost
FROM `items_details` AS a
JOIN `items` AS b ON b.id = a.item_number
WHERE a.item_number = 0101010
GROUP BY a.variant_code
ORDER BY transaction_number, variant_code

Seems pretty simple.
DB::table('items_details as a')
->join('items b', 'b.id', '=', 'a.item_number')
->select([
'a.transaction_number',
'a.date',
'a.item_number',
'b.desc',
'a.variant_code',
DB::raw('sum(a.quantity) AS quantity'),
'a.cost'
])
->where('a.item_number', '=', 10101010)
->groupBy('a.variant_code')
->orderBy('transaction_number')
->orderBy('variant_code');
Note: Not Tested

Related

Join 2 Temp tables laravel

I have following temp tables I wanna join them In query builder but I am failing to do so. I wanna join these 2 tables so I can do i1.imp/i2.imp
$subQuery1 = MyModel::query()
->from("table as i1")
->select(
\DB::raw('sum(col) as col1'),
\DB::raw('co1')
)->where('stamp', '>=', '2022-03-01 14:25:00')
->where('stamp', '<', '2022-03-07 14:30:00')
->groupBy(
'co1'
);
$subQuery2 = MyModel::query()
->from("table as i2")
->select(
\DB::raw('sum(col) as col1'),
\DB::raw('co1')
)->where('stamp', '>=', '2022-03-01 14:20:00')
->where('stamp', '<', '2022-03-07 14:25:00')
->groupBy(
'co1'
);
You can use from, fromSub or table and pass in a subquery instead of a table.
You can do the same with joinSub for joins.
You need to provide an alias though.
For example, to use $subquery1 as the main table and join it with $subquery2, the resulting query could look like this:
$results = DB::query()
->select(.....)
->fromSub($subquery1, 'i1')
->joinSub($subquery2, 'i2', function ($join) {
$join->on('i1.col', '=', 'i2.col');
// ->orOn(....)
});
->where(....)
->get();
Laravel 9.x API - fromSub
Queries - Subquery Joins

How to write this SQL query with Laravel elequoent

I tried this in laravel, but it's not working. I can't get it to work it's working when I use it straight on PHPMyAdmin
SELECT service,
count(*) as total_count,
sum(if(status ='Successful',1,0)) as successful_count,
sum(if(status ='Failed',1,0)) as failed_count
FROM `wallet_ledgers`
WHERE operator = "-"
AND user_id = 5
group by service
this is the desired output The way the table should look
You can use DB::raw
Link: Laravel-raw-expressions
$result = DB::table('wallet_ledgers')
->select(DB::raw("service, count(*) as total_count, sum(if(status ='Successful',1,0)) as successful_count, sum(if(status ='Failed',1,0)) as failed_count"))
->where([
[ 'operator', '=', '-'],
['user_id', '=', '5'],
])
->groupBy('service')
->get();

How to convert this queryto Laravel ORM

Hi guys I'm new learner Laravel.
I can not convert belowed SQL query, please help me to solve the problem.
SQL query is worked fine just I want to convert it Laraver Eloquent ORM.
select distinct u.*, d.user_id, r.region_name from users as u
left join devices as d on d.user_id = u.id
left join region as r on r.region_id = u.region_id
where d.user_id is null and u.`role` = 3
order by u.id asc
Here you go:
DB::table('users as u')
->select('u.*', 'd.user_id', 'r.region_name')
->distinct()
->leftJoin('devices as d', 'u.id', '=', 'd.user_id')
->leftJoin('region as r', 'u.region_id', '=', 'r.region_id')
->whereNull('d.user_id')
->where('u.role',3)
->oldest('u.id')
->get();

Laravel Left Join Query

I am using laravel 5.3 and I have some left join query with error in laravel query method.
This is my normal query
SELECT bran.branchName,sch.schoolName From m_schoolbranch bran
LEFT JOIN m_students stu ON stu.schoolNo=bran.schoolNo AND stu.branchNo=bran.branchNo
LEFT JOIN m_school sch ON sch.schoolNo=stu.schoolNo where stu.userNo='0000000001';
And this is my new laravel Query
DB::table('m_schoolbranch')
->join('m_students', 'm_schoolbranch.schoolNo', '=', 'm_students.schoolNo')
->join('m_students', 'm_schoolbranch.branchNo', '=', 'm_students.branchNo')
->join('m_school', 'm_schoolbranch.schoolNo', '=', 'm_school.schoolNo')
->select('m_school.schoolName', 'm_schoolbranch.branchName')
->where('m_students.userNo',$userNo)
->get();
In these query I need to match two column in table m_students so I put like this
->join('m_students', 'm_schoolbranch.branchNo', '=', 'm_students.branchNo')
But i show error...
Tables in the query need to have unique names, otherwise the DB has no way of knowing which m_schoolbranch should be used when evaluating m_schoolbranch.schoolNo.
You could use unique table aliases in your join statements but I recommend using multiple conditions on the join. Just like you use in your original SQL query. See here: https://stackoverflow.com/a/20732468/4437888
DB::table('m_schoolbranch')
->join('m_students', function($join)
{
$join->on('m_schoolbranch.schoolNo', '=', 'm_students.schoolNo');
$join->on('m_schoolbranch.branchNo', '=', 'm_students.branchNo');
})
->join('m_school', 'm_schoolbranch.schoolNo', '=', 'm_school.schoolNo')
->select('m_school.schoolName', 'm_schoolbranch.branchName')
->where('m_students.userNo',$userNo)
->get();

Laravel ordering results of a left join

I am trying to replicate the below SQL in Laravels Eloquent query builder.
select a.name, b.note from projects a
left join (select note, project_id from projectnotes order by created_at desc) as b on (b.project_id = a.id)
where projectphase_id = 10 group by a.id;
So far I have:
$projects = Project::leftjoin('projectnotes', function($join)
{
$join->on('projectnotes.project_id', '=', 'projects.id');
})
->where('projectphase_id', '=', '10')
->select(array('projects.*', 'projectnotes.note as note'))
->groupBy('projects.id')
->get()
which works for everything except getting the most recent projectnotes, it just returns the first one entered into the projectnotes table for each project.
I need to get the order by 'created_at' desc into the left join but I don't know how to achieve this.
Any help would be much appreciated.
Your subquery is unnecessary and is just making the entire thing inefficient. To be sure though, make sure this query returns the same results...
SELECT
projects.name,
notes.note
FROM
projects
LEFT JOIN
projectnotes notes on projects.id = notes.project_id
WHERE
projects.projectphase_id = 10
ORDER BY
notes.created_at desc
If it does, that query translated to the query builder looks like this...
$projects = DB::table('projects')
->select('projects.name', 'notes.note')
->join('projectnotes as notes', 'projects.id', '=', 'notes.project_id', 'left')
->where('projects.projectphase_id', '=', '10')
->orderBy('notes.created_at', 'desc')
->get();

Resources