【问题标题】:Laravel Eloquent using "with" with conditionsLaravel Eloquent 使用带有条件的“with”
【发布时间】:2016-06-25 16:45:25
【问题描述】:

我有两张表,比如 Products 和 Biddings,其中一个产品可以被许多用户竞标。自然我有两个模型:

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

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

所以,假设我想以最高出价获得所有产品,我做了这样的事情。

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

这很好,但我有点想用雄辩的方式来做。那么如何将 Query Builder 方式转换为 Eloquent 呢?我目前正在处理此问题,但不知道如何设置“最大”条件。

$productBidding = Products::with('biddings')
            ->get();

【问题讨论】:

    标签: php laravel eloquent


    【解决方案1】:
    $productbinding=Bidding:with('product')
                  ->get();
    
    foreach($productbinding as $productbind) 
    {
       echo $productbind->product->name;  // example
    }
    

    【讨论】:

    • 这不是我的意思,当我使用 ::with 来“加入”投标和产品时,我只想获得价格最高的投标。
    • Product 和 Bidding 模型之间的关系创建。使用调用上述模型。您必须使用模型关系。关系,看你的工作。
    【解决方案2】:

    我会将最高出价提取到 Product 模型上的单独函数中,如下所示:

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

    然后获取产品并获得最高出价:

    $products = Product::get();
    
    foreach ($products AS $product) {
        echo $product->highestBid();
    }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-12
    • 2019-07-08
    • 2022-07-06
    • 2020-08-15
    • 1970-01-01
    • 2020-04-21
    • 1970-01-01
    • 2017-04-01
    相关资源
    最近更新 更多