How to write this SQL query with Laravel elequoent - laravel

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

Related

How to write SQL Function where YEAR(<date_column_name>) in laravel controller

I want to fetch data from database which has booking year is 2022, and the column I have is tanggal_take whose value format is 'Y-m-d', so I want to use SELECT * FROM table_name WHERE YEAR(tanggal_take) = "2022"; How to write it in laravel controller using Eloquent?
here is my code now
$data = Booking::join('users', 'users.id', '=', 'bookings.id_member')
->join('packages', 'packages.kode_paket', '=', 'bookings.kode_paket')
->where( DB::raw('YEAR(bookings.tanggal_take)'), '=', $request->range )
->get(['bookings.*', 'packages.*', 'users.*']);
The result is 0 but in database i have 4 datas with year 2022. I also already change ->where( DB::raw('YEAR(bookings.tanggal_take)'), '=', $request->range ) to ->whereYear('bookings.tanggal_take', '=', $request->range ) but still 0 result. Any hint? I will also looking for documentation by my self rn. Thanks

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

Laravel - How to Convert MySQL query to Laravel Eloquent

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

laravel execute subquery query and get count

how select query like this in Laravel -
Select t.*, count(Select * from persons person
where person.user_id = t.id) from users t
try:
DB::table('users')
->selectRaw('*, count(SELECT * FROM persons WHERE persons.user_id = users.id)')
->get();
In my opinion to count data of other table, you can use join table combining with group. It's same as your query. You can do this:
$users = DB::table('users')
->join('persons', 'users.id', '=', 'persons.user_id')
->select('users.*', count(persons.user_id))
->groupBy('persons.user_id')
->get();
I hope this can help you.

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