Laravel SQL Query difficult - php

I can't "translate" the SQL Query below to Laravel, how I can make this?
SELECT SUM(transactions.amount) AS total, products.name
FROM transactions, product_stock, product_catalog, products
WHERE transactions.id_product_stock = product_stock.id_prodct_stock
AND product_stock.id_product_catalog = product_catalog.id_product_catalog
AND product_catalog.id_product = products.id_produto
GROUP BY (products.name);
I tried this (returns error):
Transaction::join('product_stock', 'transactions.id_product_stock', '=', 'product.stock.id_product_stock')
->join('product_catalog', 'product_stock.id_product_catalog', '=', 'product_catalog.id_product_catalog')
->join('products', 'product_catalog.id_product', '=', 'products.id_product')
->groupBy('products.name')
->get([ DB::raw('SUM(transactions.amount) AS total'), DB::raw('products.name as name')]);
And this (returns empty):
DB::raw('select SUM(transactions.amount) AS total, products.name
from transactions, product_stock, product_catalog, products
where transactions.id_product_stock = product_stock.id_prodct_stock
and product_stock.id_product_catalog = product_catalog.id_product_catalog
and product_catalog.id_product = products.id_produto
group by (products.name)');
Anyone can help me?

If you want to run the raw query (and for a complex query like this, I would stick with the raw SQL because I'm more comfortable with that), what you need to do is this:
$value = DB::select('select SUM(transactions.amount) AS total, products.name
from transactions, product_stock, product_catalog, products
where transactions.id_product_stock = product_stock.id_prodct_stock
and product_stock.id_product_catalog = product_catalog.id_product_catalog
and product_catalog.id_product = products.id_produto
group by (products.name)'
);
Here's the documentation for use of the DB::select() method.
DB::raw() is used to mark part of a larger query expression as raw SQL. See http://laravel.com/docs/queries#raw-expressions for details & examples.

quick checking their documentation it looks like you want to run your entire query as a raw expression.
http://laravel.com/docs/queries#raw-expressions
hth

Related

how to pass a pure sql query to laravel eloquent

This SQL:
SELECT COUNT(*) AS total_see_all_video
from users u
WHERE 7 = (SELECT COUNT(*) FROM lecciones_users lu WHERE lu.uuid = u.uuid)
I tried this code but did not work:
$data = LeccionesUsers::select(
DB::raw('COUNT(*) AS total_ase_vis_videos'),
DB::raw('where 7 = (SELECT COUNT(*) FROM lecciones_users where leccion_users.uuid = users.uuid)')
)
->join('users', 'lecciones_users.uuid', '=', 'users.uuid')
->get();
Your issue is that you are not correctly forming your query. You can do ->toSql(); instead of ->get(); and you would see the final SQL (would definitely not be the same as the one you wrote first).
So, you should have this to have the same SQL:
$total_see_all_video = LeccionesUsers::whereRaw('7 = (SELECT COUNT(*) FROM lecciones_users where leccion_users.uuid = users.uuid)')
->count();
Please, try my query (and also run ->toSql() to see if you have a correct SQL).
I would still recommend to use relationships and it is very weird to do 7 = query.
You can use
DB::query()->fromSub('Raw sql query here..')
and then can perform actions on this.For the reference you can use the documentation fromSub
You can also look into this convert this where break this query to parts to be used accordingly. You can use this section for the reference purpose:
Laravel-Raw-Expressions
Hope this will help you with the result.

Laravel Query Builder returns no results while generated SQL works perfect

I am actively working on a laravel project and have ran into some issues with the Query Builder. I am trying to avoid using DB::Raw but it is looking like I may need to.
$query = app($this->model());
$query = $query->select(['last_name', 'first_name', 'birthday'])
->distinct()
->leftJoin('enrollments', 'students_meta.uid', '=', 'enrollments.student_uid')
->whereIn('enrollments.type', $types)
->where('enrollments.startdate', '<=', "'{$today}'")
->where(function ($join) use ($today) {
$join->where('enrollments.dropdate', '>=', "'{$today}'")
->orWhereNull('enrollments.dropdate');
});
// todo: add viewBy filter
$query = $query->where('birth_month', '=', Carbon::today()->month);
$query = $query->orderBy('last_name')->orderBy('first_name');
$models = $query->get();
The above query builder generates the following SQL :
SELECT distinct `last_name`, `first_name`, `birthday`
FROM `students_meta`
LEFT JOIN `enrollments` ON `students_meta`.`uid` = `enrollments`.`student_uid`
WHERE `enrollments`.`type` IN ('ACTIVE', 'active')
AND `enrollments`.`startdate` <= '2019-10-29'
AND (`enrollments`.`dropdate` >= '2019-10-29' OR `enrollments`.`dropdate` IS NULL)
AND `birth_month` = 10
ORDER BY `last_name` asc, `first_name` asc;
The generated SQL is perfect based on the old code I'm moving from and produces the expected results. If I move some things around, it seems I can get the query builder to return results, but they're not the correct ones. I've looked at other questions/answers about this kind of problem and tried multiple scenarios of moving the join/changing the where's around, still no luck.
Any suggestions? (other than taking the generated sql and running it in DB::Raw()
$query = $query->orderBy('last_name')->orderBy('first_name')->get();
Your query worked fine but you didn't output it.
You can also use ->get()->toArray(); to retrieve the data in array format
Remove your quotes from around $today. The third (or second, if you eliminate the comparison operator) parameter of the where clause sends the values as a parameter in a prepared statement . So
"'{$today}'"
would look like this in a straight query:
where enrollments.startdate <= "'2019-10-29'"
So change your query to
->where('enrollments.startdate', '<=', $today)
Make sure you remove the quotes from all instances like this in your query.

Laravel Eloquent join with IN clause

I'm currently trying to use the Eloquent query builder to create a join with multiple clauses, one of which being an IN clause.
The type of query I would like to create would be
SELECT * FROM trusts t
LEFT JOIN trust_group tg ON tg.trust_id = t.id
AND tg.group_id IN (1,2,4)
I've tried
->leftJoin('trust_group', function($join) {
$join->on('trust_group.trust_id', '=', 'trusts.id');
$join->on('trust_group.group_id', 'IN', [1,2,4]);
})
which results in
and `trust_group`.`group_id` = `IN`
and I've also tried
->leftJoin('trust_group', function($join) {
$join->on('trust_group.trust_id', '=', 'trusts.id');
$join->on(DB::raw('trust_group.group_id IN (1,2,4)'));
})
but this results in a query containing something along the lines of
and trust_group.group_id IN (1,2,4) = ``
(Obviously those group IDs are for example purposes, and would by dynamic)
Can Eloquent support IN clauses on joins?
This is only part of a pretty large query, so would prefer to use the join rather than use a whereIn
As this is kinda deadlock at the moment, I am posting this as an answer until this is officially PRed. Unfortunately joining with an In clause is not yet supported officially. There are some discussions in this closed thread
You can use it as raw query :
<?php
$results = DB::select("
SELECT * FROM trusts t
LEFT JOIN trust_group tg ON tg.trust_id = t.id
AND tg.group_id IN (?)", $groupIds);
Also there is Model::hydrate($array) method if you want to have eloquent collection back from result array.
This is a pretty old post, but for anyone searching, you can now simply use where functions to build more complex joins (tested in Laravel 7) :
->leftJoin('trust_group', function($join) {
$join
->on('trust_group.trust_id', '=', 'trusts.id')
->whereIn('trust_group.group_id', [1, 2, 4])
;
})

Laravel: MYSQL query in laravel

I have a working query goes like this
SELECT s.name as status, q.name as quality, p.name process, count(*)
FROM plates
JOIN equipment_status_codes s on equipment_status_code_id = s.id
JOIN plate_qualities q on plate_quality_id = q.id
JOIN processes p on process_id = p.id WHERE project_id in
(SELECT id
from projects
WHERE name like 'SPIRIT')
GROUP BY s.name, q.name, p.name ASC with ROLLUP
This works just and returns results just fine.
Now I am trying to put this in laravel syntax, but having some difficulties.
So I was thinking something along these lines.
return Plate::select('equipment_status_codes.name as Status', 'plate_qualities.name as Quality', 'processes.name as Process')
->join('equipment_status_codes', 'plates.equipment_status_code_id', '=', 'equipment_status_codes.id')
->join('plate_qualities', 'plates.plate_quality_id', '=', 'plate_qualities.id')
->join('processes', 'plates.process_id', '=', 'processes.id')
->groupBy(DB::raw('equipment_status_code_id WITH ROLLUP'))
...
...
->get();
Would someone help out. Thanks in advance!
Update:
#Govind Samrow
I have tried this query. It works (with couple of small adjustment) But I am not getting the same results as the one I get when I run the sql query.
I included screen shots.
So when I run the sql query.
I get the following results.
When I run the laravel query.
return DB::table('plates')
->join('equipment_status_codes', 'equipment_status_code_id', '=', 'equipment_status_codes.id')
->join('plate_qualities', 'plate_quality_id', '=', 'plate_qualities.id')
->join('processes', 'process_id', '=', 'processes.id')
->whereRaw("project_id IN(SELECT id from projects WHERE name like 'SPIRIT')")
->select(DB::raw('equipment_status_codes.name as Status'), DB::raw('IFNULL(plate_qualities.name, NULL) as Quality'), DB::raw('IFNULL(processes.name, NULL) as process'), DB::raw("COUNT(*) as Total" ))
->groupBy(DB::raw('equipment_status_codes.name WITH ROLLUP', 'plate_qualities.name WITH ROLLUP', 'processes.name WITH ROLLUP', 'asc'))
->get();
I get the following.
Almost there, but I am not sure what's going on?! Any ideas?
Try following Query for Joining with where Condition
return Plate::select('equipment_status_codes.name as Status', 'plate_qualities.name as Quality', 'processes.name as Process')
->join('equipment_status_codes', 'plates.equipment_status_code_id', '=', 'equipment_status_codes.id')
->join('plate_qualities', 'plates.plate_quality_id', '=', 'plate_qualities.id')
->join('processes', function($join)
{
$join->on('plates.process_id', '=', 'processes.id')
->whereIn('project_id', DB::table('projects')->where('name','LIKE','SPIRIT')->select('id')->get()->toArray());
})
->groupBy(DB::raw('equipment_status_code_id WITH ROLLUP'))
->get();
Hope this will help.
Use whereRaw for sub query in where clause Try this:
DB::table('plates')
->join('equipment_status_codes', 'equipment_status_code_id', '=', 'equipment_status_codes.id')
->join('plate_qualities', 'plate_quality_id', '=', 'plate_qualities.id')
->join('processes', 'process_id', '=', 'processes.id')
->whereRaw("project_id IN(SELECT id from projects WHERE name like 'SPIRIT')")
->select('equipment_status_codes.name as status', 'plate_qualities.name as quality', 'q.name as quality', 'processes.name as Process', DB::raw("COUNT(*) as Total"))
->groupBy(DB::raw('equipment_status_codes.name, plate_qualities.name, processes.name ASC with ROLLUP'))->get();
Here is raw sql result of above that got with toSql():
select `equipment_status_codes`.`name` as `status`, `plate_qualities`.`name` as `quality`, `q`.`name` as `quality`,
`processes`.`name` as `Process`, COUNT(*) as Total from `plates`
inner join `equipment_status_codes` on `equipment_status_code_id` = `equipment_status_codes`.`id`
inner join `plate_qualities` on `plate_quality_id` = `plate_qualities`.`id`
inner join `processes` on `process_id` = `processes`.`id`
where project_id IN(SELECT id from projects WHERE name like 'SPIRIT')
group by equipment_status_codes.name, plate_qualities.name, processes.name ASC with ROLLUP
Note: You can use SQL output with $query->toSql() and then compare with your actual SQL query.
You may use the table method on the DB facade to begin a query. The table method returns a fluent query builder instance for the given table, allowing you to chain more constraints onto the query and then finally get the results using the get method:
Check its link and get knowladge for laravel query builder:-
https://laravel.com/docs/5.4/queries

Joining with OR in Kohana

I'm trying to combine two tables based on if they match a given pair in a many-to-many relation. I already know the SQL statement I'm trying to produce, which is functionally equivalent to the following:
SELECT columnA, columnB, ...
...
JOIN matching_table
ON ( (matching_table.id1 = table_a.id AND matching_table.id2 = table_b.id) OR
(matching_table.id1 = table_b.id AND matching_table.id2 = table_a.id) )
...
But I want to produce it using Kohana's query builder for consistency. The problem is I can't seem to find a way of creating a complex ON query. So far all I've got is
DB::select('columnA', 'columnB', ...)
...
->join('matching_table')
->on('matching_table.id1', '=', 'table_a.id')
->on('matching_table.id2', '=', 'table_b.id')
...
and this generates the first AND sequence but I can't seem to put it together with an OR.
Any suggestions?
You should be able to use where instead of on (not tested though):
->join('matching_table')
->where_open()
->where('matching_table.id1', '=', 'table_a.id')
->and_where('matching_table.id2', '=', 'table_b.id')
->where_close()
->or_where_open()
->where('matching_table.id1', '=', 'table_b.id')
->and_where('matching_table.id2', '=', 'table_a.id')
->or_where_close()

Categories