【问题标题】:Laravel 5.2, Eloquent, join Table 1 to Table 2 and bring MAX column of Table 2Laravel 5.2,Eloquent,将表 1 连接到表 2 并带上表 2 的 MAX 列
【发布时间】:2017-11-20 23:41:07
【问题描述】:

如何使用 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

基于以下上下文:

我有一个拍卖系统,其中包含用户出价的产品。这意味着一种产品可以有多个出价,而一个出价只能针对一种产品。

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

表格:

产品

  • 身份证
  • 姓名

出价

  • 身份证
  • bid_price
  • product_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');
    }
}

【问题讨论】:

    标签: laravel join eloquent laravel-5.2 max


    【解决方案1】:

    试试这个:

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

    【讨论】:

    • 谢谢,@btl。将其作为查询构建器方法牢记在心,但是否可以使用 Eloquent?
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-26
      • 2016-03-03
      • 1970-01-01
      • 1970-01-01
      • 2018-04-18
      相关资源
      最近更新 更多