Getting daily aggregates/sum sorted by day in Laravel - laravel

So getting a sum()/count() is really easy in Laravel...
but how would I look at the past month, and get the sum of rows every day?
EG...grouped by day that they were created at.
So I want to return a count such as 3, 2, 4, 5
Meaning 3 rows were created on todays date, 2 rows yesterday, 4 rows the day before...etc
How to do this in Laravel easily?
When I use the group by created_at it always just returns 1.
Anybody know how to do it?
Thanks

I've provided the same answer on another post. Shortening it:
$date = new DateTime('tomorrow -1 month');
// lists() does not accept raw queries,
// so you have to specify the SELECT clause
$days = Object::select(array(
DB::raw('DATE(`created_at`) as `date`'),
DB::raw('COUNT(*) as `count`')
))
->where('created_at', '>', $date)
->group_by('date')
->order_by('date', 'DESC')
->lists('count', 'date');
// Notice lists returns an associative array with its second and
// optional param as the key, and the first param as the value
foreach ($days as $date => $count) {
print($date . ' - ' . $count);
}

Related

Caulculating Subtruct of two Sumed variable from two unrelated Table using laravel DB::raw and groupBy months

First get Sum of cost From Finance Model groupBy month
Second get Sum of deposite From Accoountings Model groupBy month
third find the subtruction between deposite and cost and groupBy month
$data1 = Finance::select(
\DB::raw('SUM(cost) as finances_monthly'),
\DB::raw('(unit) as unit'),
\DB::raw("DATE_FORMAT(date,'%M %Y') as months"))
->where('unit', '=', $unit)
->whereBetween('date', [$start_date, $end_date])
->orderBy('date','asc')
->groupby('months','unit')->get();
// Get the Sum of cost from finance model and groupBy months
$data2 = $MonthlyPayments = Accounting::select(
\DB::raw('SUM(deposite) as deposites_monthly'),
\DB::raw('(unit) as unit'),
\DB::raw("DATE_FORMAT(payment_date,'%M %Y') as month"))
->where('unit', '=', $unit)
->orderBy('created_at','asc')
->whereBetween('payment_date', [$start_date, $end_date])
->groupby('month','unit')->get();
// get the sum of deposites from Accountings model and group by months
Problem in here how to subtract deposites_monthly from finances_monthly and groupBy months
you can use array_diff() to resolve this problem, but you should make sure the fields of both arrays are same;
$data1 = $data1->toArray();
$data2 = $data2->toArray();
$diff_data = array_diff($data1, $data2);

Getting the unique year value in Laravel

I just wanted to extract unique year value from this date type column. But I always get this error "You might need to add explicit type casts".
If there are 2020-06-23, 2020-07-01, 2019-01-02, 2019-02-05 dates, my desired output is to return the unique year values. So the output should be 2020 and 2019 only.Please help. Thank you.
Here is my code:
$year= DB::table('loans')
->select('date_release', DB::raw('YEAR(date_release) as year'))
->groupBy('year')
->get();
The query could be (returns all when there are different dates from different years);
SELECT EXTRACT(YEAR FROM loans.date_release) AS year FROM loans group by year;
The query builder will be
return DB::table('loans')
->select([DB::raw('EXTRACT(YEAR FROM loans.date_release) as year')])
->groupBy('year')
->pluck('year');
it prints following for multiple years
[2018, 2019, 2020]
I think that there are only 2 ways to get what you want
first you need add another column with name year and store data only year and your query will be like this
return DB::table('loans')
->select('year')->distinct('year');
second one is before return you should some algorithm to extract year and return only distinct year it will be like this
$year = DB::table('loans')
->select([DB::raw('YEAR(date_release) as year')])
->groupBy('year')
->value('year');
$distinct_year = array();
foreach($year as $item){
$years = date('Y', strtotime($item->year))
if(!in_array($years, $distinct_year)){
array_push($distinct_year, $years);
}
}
return $distinct_year;

How to count two related dates in Laravel using Query Builder?

I have this list of dates
I want to count the times that the time is higher than 24 hours between each dates in a row... tried with this ..
$tiempo1 = DB::table('incidencia_tiempo')
->whereTime('time', '>', '0000-00-00 24:00:00')
->count();
Beetween time and created at... I would like to count... if beetween the two times the hours are higher than 24 hours then add +1 to the count
I have to make a comparation with created_at and time and I don't know how
Use TIMESTAMPDIFF() to get the time between two datetime,
If you want to count the time high than the created_at 24 hours
$count = DB::table('incidencia_tiempo')
->where(DB::raw('TIMESTAMPDIFF(HOUR, time, created_at)'), '>', 24)
->count();
if you want to count the time difference between two datetimes high than 24 hours:
$count = DB::table('incidencia_tiempo')
->where(DB::raw('ABS(TIMESTAMPDIFF(HOUR, time, created_at))'), '>', 24)
->count();
what is yoiur mean time is higher than 24 hours?
Try This Method for Compare and Count Dates
$text_count = Text::whereBetween('created_at', [$date1, $date2])->count();
first of all you have to run simple query for getting all the data like
$tiempo1 = DB::table('incidencia_tiempo')->get();
and add one loop for this query data
$count = 0;
foreach($tiempo1 as $time) {
$start = new Carbon($time->time);
$end = new Carbon($time->created_at);
$hours = $start->diff($end)->format('%H');
if ($hours > 24){
$count++;
}
}
hope this will help :)

How to count articles for every months in current year?

I have list of months, and now i want to count articles for every month.
I have this :
$data= Articles::get()
->groupBy(function($item) {
return $item->created_at->month;
});
And for now i get data for 11 and 12, but how can i do that so that i can have list of month names and next to them have number of articles for that month?
foreach ($data as $key => $values) {
$data[$key] = $values->count();
}
$data = $clicked->toArray();
This will give you the number of articules by Month and if you want the month name as the key then
group by
$item->created_at->format('M')
instead of your group by condition

how to get all products between two dates?

how to get all products between two dates like last month products, this month products , last week products and this week products etc.
i tried with this:
// current day to start with
$start = mktime(0,0,0,date('m'), date('d'), date('Y'));;
// calculate the first day of last month
$first = date('YYYY-MM-DD',mktime(0,0,0,date('m',$start) - 1,1,date('Y',$start)));
// calculate the last day of last month
$last = date('YYYY-MM-DD',mktime(0, 0, 0, date('m') -1 + 1, 0, date('Y',$start)));
if($filter == "lastmonth"){
$collection = Mage::getModel('catalog/product')->getCollection();
$collection->addAttributeToFilter('updated_at', array('gteq' =>$first));
$collection->addAttributeToFilter('updated_at', array('lteq' => $last));
}
but i am not able to get the result :( any help ?
Modified after Daniel response !
1) First of all you need to change you date formate from 'YYYY-MM-DD' to 'Y-m-d'. This will return a date formate which magento records have.
2) There is a special condition for date as bellow mention with your example.
$collection = Mage::getModel('catalog/product')->getCollection();
$collection->addAttributeToFilter('updated_at', array('gteq' =>$first));
$collection->addAttributeToFilter('updated_at', array('lteq' => $last));
To.
$collection = Mage::getModel('catalog/product')->getCollection();
$collection->addAttributeToFilter('updated_at', array(
'from' => $first,
'to' => $last,
'date' => true,
));
I tried your code and had to swap 'lteq' and 'gteq' to make it work. The $fromdate is the lower number so you are searching for dates greater than that number.
Also you must remember to format the dates as MySQL likes it; date('Y-m-d').
PS. See the comparison operators for a full list
There is one issue with your code:
$collection->addFieldToFilter()
should be:
$collection->addAttributeToFilter()
I know that the question is little bit old but as it is quite well ranked in search engine results, I will correct the date() function that better take as arguments something like : Y-m-d H:i:s.
I hope it will help !

Resources