php - laravel get last bid from each post

124

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

312

Answer

Solution:

Addlimit() to the relation:

public function highestBids()
{
    return $this->hasMany('App\Bid')->orderBy('new_bid', 'desc')->limit(1);
}

And then get the highest bids:

$data = PostItem::with('highestBids')->get();
673

Answer

Solution:

You can write your query as:

 $items = PostItem::with(['bids' => function($query){
                    $query->orderBy('new_bid','desc');
                }])
                ->get();

And now to get highest bids of each item:

foreach ($items as $item) {
    $highest_bid = $item->bids->first(); // highest bids of $item
    if($highest_bid) {
       $new_bid = $item->new_bid;
    }
}
682

Answer

Solution:

You can usedistinct() method to get unique records. Try the query below.

$items = PostItem::with(['bids' => function($query){
             $query->distinct()
                ->select('item_id')
                ->orderBy('new_bid','desc')
                ->groupBy('item_id')
                ->get();
         }])
         ->get();
2

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

People are also looking for solutions to the problem: php - Check if something is between two values?

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.