I'm trying to group inventory results by the model and manufacturer name, display the amount of items matching and 1 result per grouping. With that said, I'd like to try and retrieve all inventory id's within the group. Wondering if this is possible... Any ideas?
FYI - I'm using Laravel, the line in question is the ->selectRaw(CambridgeID as CambridgeIDArray)
$getMatchingInventory = DB::table('inventory')
->selectRaw('*, count(*) as groupTotal')
->whereRaw("MATCH(ManufacturerNameMatch, SubCategoryNameMatch, MainCategoryNameMatch, Model_Name, Title_Override, Description_Old) AGAINST ('$final' IN BOOLEAN MODE)")
->selectRaw('CambridgeID as CambridgeIDArray')
->groupBy('Model_Name', 'ManufacturerNameMatch')
->having('Units_OnHand', '>=', '1')
->orderBy('ManufacturerNameMatch')
//->paginate(15);
->get();
try this
$getMatchingInventory = DB::table('inventory')
->select(DB::raw("GROUP_CONCAT(CambridgeID) as `CambridgeIDArray`, count(*) as `groupTotal`"))
->whereRaw("MATCH(ManufacturerNameMatch, SubCategoryNameMatch, MainCategoryNameMatch, Model_Name, Title_Override, Description_Old) AGAINST ('$final' IN BOOLEAN MODE)")
->groupBy('Model_Name', 'ManufacturerNameMatch')
->having('Units_OnHand', '>=', '1')
->orderBy('ManufacturerNameMatch')
->get();
You should be able to use GROUP_CONCAT for that, see: http://dev.mysql.com/doc/refman/5.7/en/group-by-functions.html#function_group-concat
You can use specify output format options (e.g., SEPARATOR) and use additional string manipulation as needed within the GROUP_CONCAT.
(Fyi, using raw MySQL, at least for this question, would make it easier to parse.)
Related
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.
How can I select, preferably using eloquent laravel's query builder, the latest distinct records from a table.
I have tried this query without success.
Products::where('depart_id', $depart_id)
->distinct("serial_number")
->latest()
->where('serial_number', ""); // get one of the distinct products
You can try this: distinct() will get the distinct 'serial_number'
Products::where('depart_id', $depart_id)
->where('serial_number', "")
->distinct();
The solution was to use
Products::where('depart_id', $depart_id)
->distinct('serial_number')
->orderBy('serial_number', 'desc')
->orderBy('created_at', 'desc')
->where('serial_number', "serial_number");
This ensured that the distinct returned only the unique latest record of each value.
This query is for getting other data with the highest value of date with the group by/unique. Here I used unique in place of group by.
My question is how to get min(date) and max(date) with group by/unique.
The group by/unique is for Dataset table's date field.
I have searched for this but not getting exact solution that how to get max and min date with group by/unique in laravel eloquent.
In table structure, there are multiple entries for one code so here I used group by/unique to get one record for the code.
There can be multiple dates as 02-01-2003,01-03-2007,01-01-2019, 01-07-2018... etc. with same/ different code. If I group by with code then get onmy one record per code. So here I want to select the max date [01-01-2019] and min date [02-01-2003].
Thanks in advance.
Controller:
$datasets = Dataset::where('user_id', $user_id)
->orderBy('date','desc')
->get(['code', 'access','user_id','date'])
->unique('code');
Finally I got solution but this can not be the exact solution but as I am beginner and not getting the exact solution I do this functionality as below:
I created two different queries to get min and max values.
$min_datasets = Dataset::where('user_id', $user_id)
->orderBy('date','asc')
->get(['code', 'access','user_id','date'])
->unique('code');
$max_$datasets = Dataset::where('user_id', $user_id)
->orderBy('date','desc')
->get(['code', 'access','user_id','date'])
->unique('code');
Try to select max and min date like this:
$datasets = Dataset::select('code', 'access','user_id', DB::raw('MAX(date) as max_date'), DB::raw('MIN(date) as min_date'))
->where('user_id', $user_id)
->orderBy('date','desc')
->get()
->unique('code');
$data = DB::table('table_name')->where('user_id',$user_id)
->select('code','access','user_id','date')
->whereBetween('date', [02-01-2003, 01-01-2019])
->groupBy('unique_column')
->get()
I have Users table which has under_reference column that represents by whom this user was referred.
I want to order user by having highest under_reference count. How to order by counting under reference
$data['user'] = User::orderBy('id','DESC')->get();
$data['user'] = User::select(DB::raw('count(*) as total'))
->groupBy('under_reference')
->orderBy('under_reference','DESC')
->get();
Here is the query that can help you. You can get the total users referred by a person and orderBy reference.
Use Group By for this situation, and sort from it. Here's an example.
$query = [
'name',
'email',
// store count of under_reference as total
DB::raw('count(under_reference) as total')
];
$sorted = User::groupBy('name', 'email')
->select($query)
->orderBy('total', 'desc') // remember total before, sort it by desc or asc
->get();
You can refer from laravel documentation here on raw expressions
The name and email is just an examaple, as you didn't show us what your table's column looks like. But you should get a pretty rough idea
i created another column totalref with Integer . i coded logic to update this column also with referral bonus and then orderby totalref. and it worked like magic
Try this:
$user_info = DB::table('users')
->select('under_reference',DB::raw('count(under_reference) as ur'))
->groupBy('under_reference')
->orderBy('ur','DESC')
->get();
You can try in this way also worked.
$data['user'] = DB::select('SELECT *` FROM `user` ORDER BY
CAST(`under_reference` AS decimal) DESC');
You can cast the DB column varchar to decimal in query.
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