Laravel multiple counts with condition - php

I'm tring to retrieve the totals of items from a table but can't get my head around it.
What I'm trying to achieve is this:
I have a table 'users' with the following columns:
Admin - yes/no
Moderator - yes/no
I am trying to retrieve the total of the items in the table but also the total of items in the table with admin = 'yes' OR moderator = 'yes'. The reason for this is to display the totals in one table.
Below is my sample code:
$date = new DateTime('tomorrow -360 month');
$usersPerDay = User::select(array(
DB::raw('DATE(`created_at`) as `date`'),
DB::raw('COUNT(*) as `count`'),
this is where I have the problem - Is it possible to do something like
this
DB::raw('COUNT(*) as "type" WHERE admin= "yes" OR moderator= "yes"')
))
->where('created_at', '>', $date)
->groupBy('date')
->orderBy('date', 'DESC')->get();

Related

Laravel Eloquent grab duplicates (2 or more results)

So I have the following query, which is working:
Expense::select('amount', 'date', DB::raw('COUNT(*) as `count`'))
->groupBy('amount', 'date')
->havingRaw('COUNT(*) > 1')
->get();
This is to grab all expenses that are potential duplicates (same amount and same date). However, I want to grab everything, not only the amount and date. The following is not working:
return Expense::select('name', 'amount', 'date', DB::raw('COUNT(*) as `count`'))
->groupBy('amount', 'date')
->havingRaw('COUNT(*) > 1')
->get();
This will give me this error:
SQLSTATE[42000]: Syntax error or access violation: 1055 Expression #1 of the SELECT list is not in the GROUP BY clause and contains a nonaggregated column
I have many more fields for an Expense that I want to list in my view, most importantly of course the name, but also the slug so I can link to each potential duplicate, etc.
Also, the second "issue", but not the most important one, is that with the above query, all expenses are returned in one collection. They are not grouped by date for example.
The most desirable would be to have the results somewhat like this. All potential duplicates should be grouped by the date so I can do something like this in my view:
#foreach($duplicates as $date => $expenses)
#foreach($expenses as $expense)
{{ $date }}
// List all expenses for that date.. etc.
Question 1: How would I make the above query work with all database fields, not only the date and amount?
Question 2: How would I be able to grab the potential duplicates and group them by date so I can loop over the dates and the expenses like in the above example?
Always handle column properly when doing grouping
e.i. you can specify all the fields you want to select in groupBy
// database query
$expenses = Expense::select(['amount', 'date', 'name', 'slug'])
->selectRaw('count(*) AS count')
->havingRaw('count > 1')
->groupBy(['amount', 'date', 'name', 'slug'])
->get();
// Another date grouping done in collection
return $expenses->groupBy('date');
or something like combing columns that belongs to your desired grouping
return Expense::select('date')
->selectRaw('group_concat(name) as names') // comma separated names belongs to the group
->selectRaw('group_concat(amount) as amounts') // comma separated amounts belongs to the group
->selectRaw('group_concat(slug) as slugs')// comma separated slugs belongs to the group
->selectRaw('count(*) AS count')
->havingRaw('count > 1')
->groupBy('date')
->get();
EDIT
If you only want to group them by date and still have the actual rows of duplicate, you can just add another select statement to count for date duplicate without grouping them by date in your query, and do the date grouping in collection.
e.i.
$expenses = Expense::select( ['amount', 'date', 'name', 'slug'] )
->selectRaw('(SELECT COUNT(date) FROM expenses t1 WHERE t1.date = expenses.date ) as duplicates')
->havingRaw('duplicates > 1')
->get();
return $expenses->groupBy('date');
Then the output should have another column duplicates which has the number of duplicate each date has and still has all the rows for duplicate dates

I want to find duplicate data from the database and show sum of duplicate data in laravel 8

I want to get all the data from SALES and PURCHASES table but I want to show product name for the single time and also want to show the sum of its quanitity..
How can i do this in laravel 8 ?
What will be the query ??
$stock = DB::table('products')
->join('purchases','purchases.product_id','products.id')
->join('sales','sales.product_id','products.id')
->groupBy('product_id')
->get();
I dont have your whole query but use havingRaw to find the duplicates.
$dups = DB::table('tableName')
->select('col1_name','colX_name', DB::raw('COUNT(*) as `count`'))
->join('purchases','purchases.product_id','products.id')
->join('sales','sales.product_id','products.id')
->groupBy('col1_name', 'ColX_name')
->havingRaw('COUNT(*) > 1')
->get();
Maybe something like that
$stock = DB::table('products')
->select('sales.*','purchases.*','products.name', DB::raw('products.name as `NbProduct`'))
->join('purchases','purchases.product_id','products.id')
->join('sales','sales.product_id','products.id')
->groupBy('sales.id', purchases.id)
->get();

Laravel Get Multiple Query Values

I am using Laravel , I have got some users and appointments,
some of the users doest have appointments
I need to view both of my users who has appointments and not
also, I have added a filter that is sorted by date,
while sorting I need to sort the appointment by its date and need to display the rest as it is,
is there a way to do this, this is my code
this is my code which i get the all appointments
$appointments = $this->conn->table('appointments')
->select('*','response->date','users.id as useid','appointments.id as app_id','appointments.created_at as created_at','appointments.response->date as app_data')
->join('users', 'appointments.user_id', '=', 'users.id')
this is what i am trying to do
$appointments = $appointments
->whereNull('appointments.response->datetime')
->orWhere(DB::raw( "to_char((appointments.response::json->>'datetime')::timestamp, 'MM/DD/YYYY')" ), '>=', $start_date_format)
->orWhere([DB::raw( "to_char((appointments.response::json->>'datetime')::timestamp, 'MM/DD/YYYY')" ), '<=', $end_date_format])
;
this code display ass the users but when I try to filter this won't work

Get user info from another table in laravel

I have Order table where user orders will be stored with their id and also have status of 0 / 1 to show if that order is paid by user or no.
Now I want to show in their profile that for example they have 10 orders and 3 paid.
I can get that number of total orders which is 10 but i have problem with getting the number of those 3 orders that has been paid.
Currently I have this:
$ordersd = DB::table('orders')->where('status', Auth::user()->username)->pluck('status')->count();
But it is not what I need cause I need to specified that count for me only orders with status 1 which belongs to logged user.
How do I do that?
Thanks.
Why are you comparing status with Auth::user()->username inside where condition ?
Does it makes any sense ?
$ordersd = DB::table('orders')->where('status', Auth::user()->username)
->pluck('status')->count();
So, change it to
$ordersd = DB::table('orders')
->where('user_id',Auth::user()->id)
->where('status', 1)
->count();
Hope you understand.
You should be able to do this to get the count of the paid orders:
$ordersd = DB::table('orders')
->where([ [ 'status', '=', 1 ],
[ 'user_id', '=', Auth::user()->id]
])
->count();
To get the total number of orders:
$ordersd = DB::table('orders')
->where('user_id', Auth::user()->id)
->count();

Laravel - group data by created_at field and apply pagination

I need to get previous 10 days activity of a user. In my case i am just getting 10 activity records instead of previous 10 days activity.
*My Code:
$activity = $this->where('user_id', '=', $userId)->paginate(10);
$activities = collect($activity->items())->groupBy(function($item) {
return \Carbon\Carbon::parse($item->created_at)->format('d-M-Y');
});
$activity->setCollection($activities);
dd($activity->toArray());
Output:
You are using paginate which restricts the number of results fetched from the DB. If you want to get previous 10 days activity of a user then you can write your query as:
$activity = $this->where('user_id', '=', $userId)
->where('created_at', '>=', \Carbon\Carbon::now()->subDays(10))
->get();

Categories