$device = SalesItem::where('type', '=', 1)->get()->groupBy('product_id');
There is a list of products in the database. Here I am storing the product id. The same product can be idsi. I want to get the id data of the product with the same id at most.
Sample:
ID type product_id
1 1 1
2 1 1
3 1 1
4 1 1
5 1 1
6 1 2
7 1 2
8 1 1
9 1 1
0 1 1
output: 1
here I want the output to give product id 1. I couldn't find what to do after group by. Can you guide me on this?
I don't think there is an elegant way to do this in, but this should work for you:
Note: I'm unsure of your table name.
$device = DB::table('sales_item')
->select('product_id', DB::raw('COUNT(product_id) AS magnitude'))
->where('type', 1)
->groupBy('product_id)
->orderBy('magnitude', 'DESC')
->limit(1);
It goes into the table and selected the id, type, and the COUNT() of product_id. Which it then groups by the product_id and orders by the count('product_id') from high to low.
->limit(1) is used to only select the first (read highest) value.
Related
I have two tables
field_values (with some data)
id field_id value label sort
1 1 1 Men 1
2 1 2 Women 2
3 2 3 Relationship 1
4 2 4 Chat 2
5 2 5 Friendship 3
user_interests (with some data)
user_id field_id value_id
1 1 1
1 2 4
1 2 5
I am trying to write a query where I will get user with id 1 and have field_id 2 and to be able to echo in my blade value_id 4 and 5 but not to echo those ids but to echo value of 'label' column that corresponds to value_id form user_interests table in this case 4,5 thus Chat, Friendship from field_values table in this example. Here is what I tried but I get array of six elements which are Relationship, Chat, Friendship x2. Any help is appreciated.
query:
public static function queryFunction($userId)
{
$results = DB::table('user_interests as uin')
->select(DB::raw("
fv.*,
uin.field_id, uin.value_id
"))
->join('field_values as fv', 'fv.field_id', '=', 'uin.field_id')
->where('uin.field_id', 2)
->where('uin.user_id', $userId)
->get();
dd($results);
return $results;
}
What about 2 clear steps, without join:
$user_interests = DB::table('user_interests')->select('value_id')->where('field_id', 2)->where('user_id', $userId)->get();
From this take values as array ($user_interests_values)
and than
$results = DB::table('field_values')->whereIn('value', $user_interests_values)->get();
I am using Laravel 5.4's Query Builder to perform a series of leftJoins on three tables. Here are my tables:
items
id type title visibility status created_at
-- ---- ----- ---------- ------ ----------
1 1 This is a Title 1 1 2017-06-20 06:39:20
2 1 Here's Another Item 1 1 2017-06-24 18:12:13
3 1 A Third Item 1 1 2017-06-26 10:10:34
count_loves
id items_id user_id
-- ------- -------
1 1 2
2 1 57
3 1 18
count_downloads
id items_id user_id
-- ------- -------
1 1 879
2 1 323
And here is the code I am running in Laravel:
$items_output = DB::table('items')
->leftJoin('count_loves', 'items.id', '=', 'count_loves.items_id')
->leftJoin('count_downloads', 'items.id', '=', 'count_downloads.items_id')
->where('items.visibility', '=', '1')
->where('items.status', '=', '1')
->orderBy('items.created_at', 'desc')
->select('items.*', DB::raw('count(count_loves.id) as loveCount'), DB::raw('count(count_downloads.id) as downloadCount'))
->groupBy('items.id')
->get();
When I return the results for this query, I am getting the following counts:
count_loves: 6
count_downloads: 6
As you can see, the actual count values should be:
count_loves: 3
count_downloads: 2
If I add another entry to the count_loves table, as an example, the totals move to 8. If I add another entry to the count_downloads table after that, the totals jump to 12. So, the two counts are multiplying together.
If I die and dump the query, here's what I get:
"query" => "select 'items'.*, count(count_loves.id) as loveCount,
count(count_downloads.id) as downloadCount from 'items' left join
'count_loves' on 'items'.'id' = 'count_loves'.'items_id' left join
'count_downloads' on 'items'.'id' = 'count_downloads'.'items_id'
where 'items'.'visibility' = ? and 'items'.'status' = ? group by
'items'.'id' order by 'items'.'created_at' desc"
How do I perform multiple leftJoins using Query Builder and count on several tables to return the proper sums?
NOTE:
This is intended as a HELP answer not the total absolute answer but I could not write the code in a comment. I am not asking for votes (for those who just can't wait to downvote me). I have created your tables and tried a UNION query on raw sql. I got correct results. I dont have laravel installed, but maybe you could try a UNION query in Laravel.
https://laravel.com/docs/5.4/queries#unions
select count(count_downloads.user_id)
from count_downloads
join items
on items.id = count_downloads.items_id
UNION
select count(count_loves.user_id)
from count_loves
join items
on items.id = count_loves.items_id
ScholarCard
scholar_card_id grade scholar_id
1 grade-1 1
2 grade-1 2
3 grade-2 1
4 grade-2 2
5 grade-3 1
$scholar_cards = ScholarCard::where('scholar_id','=',$scholar_id)->orderBy('scholar_card_id','DESC')->get();
I have a table for a card of grades and i want to display the latest created card.
Like for example for scholar_id 1,there are three 1 on the column.How do you display only
the scholar_id 1 with the latest or last creation.This table has only few record for simplicity.
You could use first() function. Try this:
$scholar_card = ScholarCard::where('scholar_id','=',$scholar_id)
->orderBy('scholar_card_id','DESC')
->first();
I am working on a php/mysql best before date checking system and upon creating a new check I need the system to find a best before date for a certain product by looking for it most recent closed check
I am working with a few tables to get this done:
bbcheckProducts
ID checkID productID checked bestBefore
1 1 1 1 2015-05-06
2 2 1 1 2016-07-22
3 3 1 1 2016-09-16
bbChecks
checkID userID closed
1 1 1
2 2 1
3 1 1
So when I run this query on the tables in the image above:
SELECT ID,
MAX(checkID) AS maxCheck,
bestBefore
FROM bbcheckProducts
WHERE checkID IN
(
SELECT checkID
FROM bbChecks
WHERE userID = 1
AND closed = 1
)
AND checked = 1
GROUP BY productID
ORDER BY bestbefore ASC
it returns something like this:
ID = 1
maxCheck = 3
bestBefore = 2015-05-06
so it does take the max checkID but the other values remain equal to the first occurence of productID. I want it to take the values that go together with that max ID so the result would look like this:
ID=3
maxCheck = 3
bestBefore = 2016-09-16
so how do I get my query to work like that?
NOTE: there are multiple products so product one may be in check 1 and 3 while product 2 is only in 1 so it has to take the data of product 2 from check 1 and the data of product 1 from check 3
You need to use max function on second table like this query
select * from table_name where some_colomn = 'some_value' and some_colomn
in (select max(some_colomn) from table_name2 where some_col = 'some_value' group by some_colomn)
You could join your tables to get a reduced set of all record with an check_ID existing in your bbChecks-table.
Then you can run your max(CheckID)-selection on the reduced set.
In your case this would like like that:
SELECT ID, max(checkID), bestBefore
FROM bbcheckProducts p
INNER JOIN bbChecks c ON (p.checkID = c.checkID)
WHERE UserID = 1
AND closed = 1
AND checked = 1
This returns you first of alle the records with the checkIDs 1 and 3. And then you select the max(checkID), so it returns you the checkID 3.
Hello friends I have 2 Mysql tables with 1:N relationship between category and category_Dates
Category:
ID Category Frequency
1 Cat A Half-yearly
2 Cat B Quarterly
category_Dates:
ID CatID Date
1 1 01-Jan-15
2 1 01-Jul-15
3 2 01-Jan-15
4 2 01-Apr-15
5 2 01-Jul-15
6 2 01-Oct-15
based on the category frequency I am entering number of records automatically in category_date. Eg
When category frequency = quarterly, I am entering 4 records in category_date with ID of that category. And dates will be entered later.
I am little confused if in case on wants to edit the frequency from halfyearly to yearly. How to change number of records. Please help with your valuable suggestions. I am using laravel 4 framework with mysql
best way would be with 3rd table joining Dates and Categories. See little carefully ,you can see its actually Many to Many relationship (N to N) as 1 category can have multiple dates. and one date may be part of multiple categories, like say 01-Jan-15 is part of Category 1 and 2 as well.
So use
category table
id Category Frequency
1 Cat A Half-yearly
2 Cat B Quarterly
date table
id Date
1 01-Jan-15
2 01-Apr-15
3 01-Jul-15
4 01-Oct-15
categories_dates table
ID CatID Date_id
1 1 1
2 1 3
3 2 1
4 2 2
5 2 3
6 2 4
If you change the frequency in Category table, retrieve the update category_id,
delete all from category_dates where CatId=category_id then insert the new entries in category_Dates.
Hope this help.
I assume your models are Category and CategoryDates.
let's update category id 1 from Half-yearlyto to Quarterly
$query = Category::find(1);
$query -> Frequency = 'Quarterly';
$query -> save();
return $query -> id;
in the CategoryDates model you would delete the catID = 1 and insert new data
$catID = 1;
$query = CategoryModel::where('CatId',$catId) -> delete();
$data = ['CatId' => $catID,'date' => 01-Jan-15, ....];
CategoryModel::create($data);
of course assuming that you would return the newly updated category id to your controller and call a funtionn to do the update in your CategoryModel.
Hope this help.