php - laravel get last bid from each post
I have 2 tables, Items and Bids.
Items hasMany(Bid);
Table items
- id-1
- id-2
- id-3
Table bids
- id-1 | 3
- id-1 | 4
- id-2 | 2
- id-2 | 5
- id-3 | 4
- id-3 | 6
and now I want to show the highest bid of each item.
and here is my code
$data = PostItem::with([
'bids' => function($query) {
$query->orderBy('new_bid','desc')->get();
}
])
->get();
But the problem is it will takes all bids.
But if I use this code
$data = PostItem::with([
'bids' => function($query) {
$query->orderBy('new_bid','desc')->take(1);
}
])
->get();
It will takes only 1 latest bid, do not take the latest bid of each item.
How to do it properly?
Thanks in advance
Answer
Solution:
Add
limit()
to the relation:And then get the highest bids:
Answer
Solution:
You can write your query as:
And now to get highest bids of each item:
Answer
Solution:
You can use
distinct()
method to get unique records. Try the query below.Answer
Solution:
I have the answer but it may not the best answer.
So i still with my first query and then in the view i am using @foreach. because I already sort the highest bid first, so i added @break to break foreach so it doesn't loop all result.
but I am sure there is better way to do this