Display sum of column between two years in laravel - laravel

I have following table i wants sum of all orders_qty in between two years & in two month. I am creating query as following which display only answer 4 and actual wants result 8(2,2,2,2)
orders_id orders_qty delivery_date
1 2,2, 2019-02-01
2 2,2, 2020-02-03
controller:getting qty addition month wise
$get_month_wise_details=DB::table('orders')
->select('orders_qty')
->where('order_status',6)
->whereBetween(DB::raw('DATE_FORMAT(deliver_date,"%Y-%m")'), ['2019-02','2020-02'])
->groupBy('orders_qty')
->get();
foreach ($get_month_wise_details as $month_wise_details)
{
$month_array=explode(',',$month_wise_details->orders_qty);
$month_addition=array_sum($month_array);
$sum_qty=$sum_qty+$month_addition;
}
controller:getting qty addition year wise
$get_year_wise_details=DB::table('orders')
->select('orders_qty')
->where('order_status',6)
->whereBetween(DB::raw('DATE_FORMAT(deliver_date,"%Y")'), ['2019','2020'])
->groupBy('orders_qty')
->get();
foreach ($get_year_wise_details as $year_wise_details)
{
$year_array=explode(',',$year_wise_details->orders_qty);
$year_addition=array_sum($year_array);
$sum_qty=$sum_qty+$year_addition;
}

Related

Laravel: Sum column based on relationship condition

Let's say we have two tables:
Payments
id
reason_id
amount
1
1
100
2
2
10
3
1
30
Payment Reasons
id
title
is_discount
1
Payment for something
0
2
Discount for something
1
I'd like to query payments table and sum amount column based on its relationship payment_reasons.is_discount value:
total_received
total_discounted
130
10
How to achieve this?
If you want to get the data in one db-request, I don't think there is a clean laravel-way to solve this. I've been trying out some raw mysql to get it into a working query and it would look like this:
select
sum(if(pr.is_discount = 0, p.amount, 0)) as total_received,
sum(if(pr.is_discount = 1, p.amount, 0)) as total_discounted
from payments p
join payment_reasons pr on pr.id = p.reason_id
The if statement will render if discount needs to be used per row and the sum wil simply sum all the end-results together.
Doing this in laravel with a model does not really make sence, since there are no fields in the result which your model could use anyway. In this case, using eloquent would be more (unmaintainable) code than a simple Query Builder:
$data = DB::select('
select
sum(if(pr.is_discount = 0, p.amount, 0)) as total_received,
sum(if(pr.is_discount = 1, p.amount, 0)) as total_discounted
from payments p
join payment_reasons pr on pr.id = p.reason_id
')
If you don't mind doing multiple queries to fetch the data, models make more sense:
$totalReceived = Payment
::whereHas('paymentReason', fn($q) => $q->where('is_discount', 0))
->sum('amount');
$totalDiscounted = Payment
::whereHas('paymentReason', fn($q) => $q->where('is_discount', 1))
->sum('amount');
Please note that this example will perform 4 queries, 2 on payments, and 2 on payment_reasons

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;

Count the number of replies from a comment in a given post using laravel eloquent

I have a sample comments table below:
id | parent_id | post_id
1 0 1
2 0 1
3 1 1
4 2 1
5 1 1
What I am trying to achieve is to get all comments (parent_id=0) based on post_id, and count the total replies at the same time. When a query is executed it should display like the result below:
id 1 has 2 replies
id 2 has 1 reply
Here is my sample query below and it gets all comments from the given post but the problem is, I am not sure how to count at the same time in one query.
Comment::where('parent_id', '=', 0)
->where('post_id', $postId)
->get();
Does anybody know how to fix this?
You can define a method in your Comment model class.
As follows:
public function replies()
{
return $this->hasMany('App\Models\Comment','parent_id');
}
Then you can get the number of replies using the following code:
$comments = Comment::where('parent_id', '=', 0)
->where('post_id', $postId)
->withCount('replies')
->get();
In this case, you can access the number of comments with the following code:
foreach ($comments as $comment){
$countOfReplies = $comment->replies_count;
}
I hope it helps

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

Getting daily aggregates/sum sorted by day in 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);
}

Resources