0

I have two tables, say Products and Biddings where one product can be bid by many users. Naturally I have two models:

class Product extends Model
{
    public function biddings()
    {
        return $this->hasMany('App\Bidding');
    }
}

class Bidding extends Model
{
    public function product()
    {
        return $this->belongsTo('App\Product');
    }
}

So, say I want to get all products along with the highest priced bidding I did something like this.

$productBidding = DB::table('biddings')
                 ->select('*', DB::raw('max(price) as price'))
                 ->join('products', 'products.id', '=', 'biddings.product_id')
                 ->groupBy('product_id')
                 ->get();

That works well BUT I kinda want to do it Eloquent way. So how do I convert Query Builder way to Eloquent? I am currently on this but do not know how to put the "max" condition in.

$productBidding = Products::with('biddings')
            ->get();
vitr
  • 6,766
  • 8
  • 30
  • 50
Lee
  • 3,044
  • 1
  • 12
  • 25

2 Answers2

0
$productbinding=Bidding:with('product')
              ->get();

foreach($productbinding as $productbind) 
{
   echo $productbind->product->name;  // example
}
  • That's not what I meant, when I am using ::with to "join" Bidding and Product I want to get the bidding that has the highest price only. – Lee Jun 25 '16 at 07:58
  • Product and Bidding models between relationship create. Using call the model as above. You must use model relationship. Relationship, see your job. – sebahattin çatal Jun 25 '16 at 08:08
0

I would extract the highest bid to a separate function on the Product model, like so:

public function highestBid() {
    return $this->biddings()->max('price');
}

Then fetch the products and get the highest bid:

$products = Product::get();

foreach ($products AS $product) {
    echo $product->highestBid();
}
pawelmysior
  • 3,190
  • 3
  • 28
  • 37
  • I am looking for a single Eloquent query to get the same result set as my Fluent query. What I want to achieve is similar to this http://stackoverflow.com/questions/15291506/sql-query-to-select-distinct-row-with-minimum-value but on Eloquent. – Lee Jun 25 '16 at 09:28