Reputation: 8036
How do I achieve the following equivalent SQL query using Laravel (5.2) and Eloquent...
SELECT
products.id
,products.name
,MAX(bids.bid_price) as maximum_bid
FROM products
INNER JOIN bids
ON products.id = bids.product_id
GROUP BY products.id
Based on the following context:
I have an auction system that has products that users bid on. Meaning one product can have many bids, and one bid can only be for one product.
Now I want to retrieve a product with its current maximum bid
TABLES:
products
bids
MODELS:
Product
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
/**
* A Product has many bids
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function bids()
{
return $this->hasMany('App\Bid');
}
}
Bid
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Bid extends Model
{
/**
* A Bid belongs to a product
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function product()
{
return $this->belongsTo('App\Product','product_id');
}
}
Upvotes: 0
Views: 298
Reputation: 8036
This worked using Eloquent.
Product::join('bids', 'products.id', '=', 'bids.product.id')
->select(['products.id', 'products.name', DB:raw('MAX(bids.bid_price) as maximum_bid')])
->groupBy('products.id')
->where('products.id', '=', 123)
->get();
Upvotes: 0
Reputation:
Try this:
DB::table('products')
->select(['products.id', 'products.name', DB:raw('MAX(bids.bid_price) as maximum_bid')])
->join('bids', 'products.id', '=', 'bids.product.id')
->groupBy('products.id')
->get();
Throw a where clause in for a specific product:
DB::table('products')
->select(['products.id', 'products.name', DB:raw('MAX(bids.bid_price) as maximum_bid')])
->join('bids', 'products.id', '=', 'bids.product.id')
->groupBy('products.id')
->where('products.id, '=', 123)
->get();
Upvotes: 1