I've got two tables: listings, which holds the details of a product, and bids, which holds the bid history of the site.
For brief relevance, imagine that listings has the following fields: name, category_id, tagline, short_description, and seller_notes.
In bids we have two relevant fields: listing_id, and bid_amount.
For reasons relevant elsewhere, this needs to be in Eloquent as I need access to the model.
The issue seems to be with the MAX bid amount line or the evaluation of the bid_amount—no matter how I approach it, I always end up with an irrelevant result, but there's no apparent error that I can see.
$listings = \App\Listing::join('bids', 'listings.id', '=', 'bids.listing_id')->select('listings.*','MAX(bids.bid_amount)');
if( !empty($request->keyword) ) {
$listings = $listings->where('listings.name','LIKE','%'.$request->keyword.'%')
->orWhere('listings.tagline','LIKE','%'.$request->keyword.'%')
->orWhere('listings.short_description','LIKE','%'.$request->keyword.'%')
->orWhere('listings.seller_notes','LIKE','%'.$request->keyword.'%');
}
if( !empty($request->category) ) {
$listings = $listings->where('listings.category_id','=',$request->category);
}
if( !empty($request->minimum_bid) && !empty($request->maximum_bid) ) {
$listings = $listings->whereBetween('bid_amount', [$request->minimum_bid, $request->maximum_bid]);
} else {
if( !empty($request->minimum_bid) ) {
$listings = $listings->where('bid_amount', '>', $request->minimum_bid);
}
if( !empty($request->maximum_bid) ) {
$listings = $listings->where('bid_amount', '<', $request->maximum_bid);
}
}
The search is to find results with a current highest bid between minimum_bid and maximum_bid (fields from the search box). The problem presenting is that there may be multiple listings (listing_id) that have a current highest bid (MAX(bid_amount)) between those amounts. I want to display the listings where the MAX(bid_amount) for that bid.listing_id is between minimum_bid and maximum_bid. This could potentially result in multiple listings.
The equivalent MySQL query should be:
SELECT *
FROM listings
JOIN (SELECT listing_id,
Max(bid_amount) AS bid_amount
FROM bids
GROUP BY listing_id) bids
ON bids.listing_id = listings.id
WHERE ( listings.NAME LIKE '%keyword%'
OR listings.tagline LIKE '%keyword%'
OR listings.short_description LIKE' %keyword%'
OR listings.seller_notes LIKE '%keyword%' )
AND ( bids.bid_amount > minimum_bid )
AND ( bids.bid_amount < maximum_bid )
I know this is something stupid that I'm doing wrong, I just could really use a fresh set of eyes. Thank you for any help you can provide.
listing.id = bids.id?listingswhere theMAX(bid_amount)for thatbid.listing_idis betweenminimum_bidandmaximum_bid. This could potentially result in multiple listings.