Laravel 5.2, Eloquent, 加入 Table 1 到 Table 2 并带上 Table 2 的 MAX 列

Laravel 5.2, Eloquent, join Table 1 to Table 2 and bring MAX column of Table 2

如何使用 Laravel (5.2) 和 Eloquent...

实现以下等效的 SQL 查询
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

基于以下上下文:

我有一个拍卖系统,其中包含用户出价的产品。表示一个产品可以有多个出价,一个出价只能针对一个产品。

现在我想检索具有当前最高出价的产品

表格:

产品

出价

型号:

产品

<?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');
    }
}

出价

<?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');
    }
}

试试这个:

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();

为特定产品添加 where 子句:

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();

这使用 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();