I have dates in a calendar and am accessing them with the below, they have a category relationship with a Category table and a relationship with a CalEvent table.
$cal_dates = CalDate::whereBetween('date', array($from, $to))
->orderBy('date')
->orderBY('start')
->get();
This returns a list sorted by start date within a range. All good so far and a returned row looks like the below, I can access Category and CalEvent fine i.e. $cal_date->CalEvent->description.
{
"id":"406",
"cal_event_id":"77",
"start":"00:00:00",
"finish":"00:00:00",
"date":"2014-04-06",
"created_by":"0",
"updated_by":"0",
"created_at":"2013-09-21 04:43:25",
"updated_at":"2013-09-21 04:43:25"
}
What I need to is an object like below for my view with the relationships to Category and Cal_Dates table intact:
cal_dates
'12th Feb 2014'
'Array of dates related to category 1 for 12th Feb'
'Array of all other dates not related to category 1 for 12th Feb'
'13th Feb 2014'
'Array of dates related to category 1 for 13th Feb'
'Array of all other dates not related to category 1 for 13th Feb'
...
Any advice much appreciated...
Try this:
$cal_dates = $cal_dates->sortBy(function($cal_date)
{
return $cal_date->date;
});
or modify your query:
$cal_dates = CalDate::with('category')
->whereBetween('date', array($from, $to))
->orderBy('date')
->orderBY('start')
->get();
Then in your view you can access the relationship like the following:
#foreach($cal_dates as $cal_date)
<li> {{ $cal_date->date }} </li>
<!-- category data -->
<li> {{ $cal_date->category->something }}
#endforeach
Related
I have 2 tables, 'Invoice table', and related 'linesInvoice' table.
To simplify it, I will say that the invoice lines table has only the invoice_id field for the relationship and total for the price.
Now, I need to get last invoices, with his totals (totals, is the sum of column 'total' in every line).
I've tried many examples, but none works for me correctly.
Controller:
$lastInvoices = Invoice::latest()
->limit(10)
->with(['invoiceLines'])->get();
Model for relation
public function invoiceLines()
{
return $this->hasMany(InvoiceLines::class, 'invoice_id');
}
The result that I want for example looks like:
[
Invoice_id => 1
total => 500 //Sum of totals in lines of invoice 1
],
[
Invoice_id => 2
total => 300 //Sum of totals in lines of invoice 2
],
I guess I could go through all the invoices and lines in foreachs and make the sum. But I hope it can be done in the same query
You can use withSum method. This method accept the relation method as first argument and column to sum as second argument
$lastInvoices = Invoice::latest()
->limit(10)
->withSum('invoiceLines','your_column_name')
->with(['invoiceLines'])->get();
Laravel 8^
Invoice::with('invoiceLines')->latest()->first()->invoiceLines()->sum('totle');
totle colme table invoiceLines
i am display graph of sum of qty datewise it works but now i want to display graph in which sum of qty of month and year combine selection. My date is stored in format 2020-02-14 and i want to display sum of qty of 2020-02 that is from 2019-02 to 2020-09. I tried lot of works. I am getting graph date wise but now i want to year and month combine
For date selection the query as
$get_details=DB::select('SELECT sum(orders_qty) as sum_of_qty,deliver_date FROM `orders` WHERE deliver_date between ? AND ? GROUP BY deliver_date',[$data['start_date'],$data['end_date']]);
For yearand month selection i need query
I tried like this
$data=$req->all();
$results = DB::table('orders')
->select(DB::raw('DATE_FORMAT(deliver_date,"%y-%m") as deliver_date'),DB::raw('SUM(orders_qty) as sum_of_qty'))
->whereBetween('deliver_date',[$data['start_year_month'],$data['end_year_month']])
->groupBy('deliver_date')
->get();
$date[start_year_month]='2019-02' $date[end_year_month]='2019-05' and actual database date='2019-02-14'
plz need query
First, use %Y-%m instead of %y-%m;
Secondly, you are rewrite your field's name, so group by will not using the name that has been rewritten, you need to specify DB::raw('DATE_FORMAT(deliver_date,"%Y-%m")
So the query like this:
$data=$req->all();
$results = DB::table('orders')
->select(DB::raw('DATE_FORMAT(deliver_date,"%Y-%m") as delivery_date'),DB::raw('SUM(orders_qty) as sum_of_qty'))
->whereBetween(DB::raw('DATE_FORMAT(deliver_date,"%Y-%m")'), [$data['start_year_month'],$data['end_year_month']])
->groupBy(DB::raw('DATE_FORMAT(deliver_date,"%Y-%m")'))
->get();
You can try this!
$results = DB::table('orders')
->select(DB::raw('DATE_FORMAT(deliver_date,"%y-%m") as deliver_date'),DB::raw('SUM(orders_qty) as sum_of_qty'))
->whereBetween('deliver_date',[$data['start_year_month'],$data['end_year_month']])
->groupBy(function ($val) {
return Carbon::parse($val->start_time)->format('y'); });
I want to display the total payments overall, and total payments for this month using only one variable.
Controller
$payments = Payment::where('user_id', auth()->user()->id)->get();
return view('subscribers.payments', compact(['payments']));
View
<label>Total payments</label>
<p>{{ $payments->sum('amount') }}</p>
<label>For this month</label>
<p>{{ $payments->whereMonth('created_at', now()->month)->sum('amount') }}</p>
Actually the total payments overall displayed. But the "for this month" it is not working and returns me an error below:
Method Illuminate\Database\Eloquent\Collection::whereMonth does not exist.
Someone could tell me where I went wrong? and proper way to achieve this?
Isn't querying by month alone going to create a problem later when you have more than one year of data? I would just use the start of the current month.
<p>{{ $payments->where('created_at', '>=', now()->startOfMonth())->sum('amount') }}</p>
so whereMonth is unfortunately only available with the query builder. You could filter the items after they've been retrieved:
$payments->filter(function ($payment) {
return $payment->created_at->month == now()->month;
})->sum('amount')
Is it possible to sort the results of a select by relationships?
I have a one to many relationship. A product has multiple items. And each item has a price. I need to fetch the products, however the ordering of the products must be for the price of the items
Let me give you an example:
Product::with(['items'])->whereHas('items', function ($query) {
$query->orderBy('price', 'desc')
})->get();
It would be something like that. But I need to sorting the products per prices that are inside the items.
if my database has the following:
product 1
item $ 1.2
item $ 2.0
product 2
item $ 3.0
item $ 0.5
product 3
item 1.0
I need a return:
product 2
item $ 3.0
item $ 0.5
product 3
item 1.0
product 1
item $ 1.2
item $ 2.0
because it was considered the lowest item of each product. How could I do this query using enloquent?
can you try this on your query.
Product::withCount(['items as ItemTotalAmount' => function($q){
$q->select(DB::raw("SUM(price)"));
}])
->with('items')
->orderBy('ItemTotalAmount', 'ASC')->get();
In this query, it sum first the Items Price and put the Total in the Alias ItemTotalAmount
Then I used orderBy in the ItemTotalAmount to sort the products that has more total of items price.
whereHas is typically used to query relationship existence with additional where() conditions. From the documentation:
If you need even more power, you may use the whereHas and orWhereHas
methods to put "where" conditions on your has queries. These methods
allow you to add customized constraints to a relationship constraint.
In your particular case, you just want to order the eager-loaded relations. As such, the following should do the trick instead.
$product = Product::with(['items' => function($query) {
$query->orderBy('price', 'asc');
}])
->get();
I encountered a problem with pagination in my Laravel app.
Normally, when I want to use Laravel pagination with let's say 3 rows for one page, I use Eloquent method paginate/simplePaginate in combination with method latest() like so:
//MyController.php
$posts= Post->latest()->paginate(3);
//MyView.blade.php
#foreach ($posts as $post)
{{ $post->id }}
#endforeach
{{ $posts->links() }}
So when i have 6 posts in my database and I use Laravel pagination + Infinite scroll, that becomes:
6
5 (1. page)
4
--- ('page separator')
3
2 (2. page)
1
But, if user inserts new row into database table before I reach page 2,
the collection shifts and second page of data becomes:
6
5 (1. page)
4
--- POST WITH ID 4 IS DUPLICATED BECAUSE OF SHIFT IN COLLECTION
4
3 (2. page)
2
So, for example --- if user inserts three new rows into database before I reach paginator, then the second page will output the same three table rows as my current first page, but i'd like to output the remaining table rows:
6
5 (1. page)
4
--- AT SOME TIME BEFORE PAGINATION WAS TRIGGERED, POST WITH ID '7' HAS BEEN ADDED
3
2 (2. page) - continues normally with remaining rows (pagination ignores newly added row)
1
Is there any workaround for this problem?
Thanks.
I solved this issue by asking for the first record id of the first page served
// {initial query} $records->orderBy('created_at', 'desc');
if(is_int($last_id)){
$records = $records->where('id', '<=' , $last_id);
}
$records = $records->paginate($per_page);
This way, the paginator get's records starting from that id, ignoring new records
You could try this:
$posts= Post->orderBy('id', 'desc')
->distinct()
->paginate(3);