首页 > 解决方案 > Laravel Model Eloquent 将结果列表更改为分组数据

问题描述

我一直在互联网上四处寻找,但这个问题似乎并不多。

简而言之,我有一个模型,它与存储在数据库中的报价有关。这些价格是通过与其他模型的各种关系调用的,这就是为什么我没有尝试在从控制器运行查询时可能能够分组的东西。无论如何,这些价格带有我感兴趣的“个人”和“商业”两个标志。目前查询模型将返回如下数据:

{
    [
        {'offer_id': 1, 'price': 345.30, 'personal': 1, 'business': 0},
        {'offer_id': 1, 'price': 432.40, 'personal': 0, 'business': 1},
        {'offer_id': 1, 'price': 464.50, 'personal': 1, 'business': 0},
        {'offer_id': 1, 'price': 634.20, 'personal': 0, 'business': 1}
    ]
}

但我真正想要实现的是:

{
    "personal":
        [
            {'offer_id': 1, 'price': 345.30, 'personal': 1, 'business': 0},
            {'offer_id': 1, 'price': 464.50, 'personal': 1, 'business': 0},
        ],
    "business":
        [
            {'offer_id': 1, 'price': 432.40, 'personal': 0, 'business': 1},
            {'offer_id': 1, 'price': 634.20, 'personal': 0, 'business': 1}
        ]
}

这是模型:

<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class OfferPrice extends Model {

    protected $fillable = ['offer_id', 'price', 'personal', 'business'];


    public function offers()
    {
        return $this->belongsTo('App\Offer');
    }

}

任何帮助是极大的赞赏!

标签: laraveleloquentmodellumen

解决方案


您可以使用 Collection 方法groupBy。默认情况下,任何返回多个模型的 Eloquent 查询都会出现在一个集合中。

$prices = OfferPrice::all()->groupBy(function ($offer) {
    return $offer->personal === 1 ? 'personal' : 'business';
});

你可以把它放在这样的函数中

class OfferPrice extends Model {

    ...

    public static function groupPersonalBusiness() 
    {
        return self::all()->groupBy(function ($offer) {
            return $offer->personal === 1 ? 'personal' : 'business';
        });
    }
}

然后像这样使用它

$prices = OfferPrice::groupPersonalBusiness();

如果您有报价并定义了反向关系,您也可以在那里使用 groupBy,因为关系也返回一个集合。

class Offer extends Model {

    public function offerPrices() 
    {
         return $this->hasMany('App\OfferPrice');
    }
}

然后像这样使用它

$prices = Offer::find(1)->offerPrices->groupBy(function ($offer) {
            return $offer->personal === 1 ? 'personal' : 'business';
          });

推荐阅读