Laravel 模型 Eloquent 将结果列表变异为分组数据

Laravel Model Eloquent mutate result list to grouped data

我一直在网上搜索,但似乎没有太多关于这个问题的内容。

简而言之,我有一个与存储在数据库中的报价相关的模型。这些价格是通过与其他模型的各种关系调用的,这就是为什么我没有尝试在 运行 来自控制器的查询时可能能够分组的原因。无论如何,这些价格带有我感兴趣的两个标记 'personal' 和 'business'。目前查询模型将 return 数据如下:

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

}

非常感谢任何帮助!

您可以使用收集方法groupBy。默认情况下,任何 Eloquent 超过一个模型的 return 查询都将出现在一个集合中。

$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,因为关系也是 return 一个集合。

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