【问题标题】:Laravel Model Eloquent mutate result list to grouped dataLaravel Model Eloquent 将结果列表更改为分组数据
【发布时间】:2019-09-06 20:56:14
【问题描述】:

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

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

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

}

非常感谢任何帮助!

【问题讨论】:

    标签: laravel eloquent model lumen


    【解决方案1】:

    您可以使用收集方法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';
              });
    

    【讨论】:

    • 感谢您的回复,但我已经尝试了几天来应用它。我以前没用过集合,请问你有更多的例子吗?
    • @Paul 它的哪一部分不起作用?在不知道哪里出错的情况下,我不确定我可以添加什么以使其更清楚。
    • 我创建了一个集合 OfferPriceCollection,其中包含您的脚本的函数 groupPersonalBusiness()。然后将 newcollection 函数添加到调用集合的 OfferPrice 模型中。我是根据 Laravel Collection 文档完成的
    • 啊,混乱。你不需要做任何这些。我的示例是为使用您发布的原始代码而编写的。但现在重读它,我发现需要进行一次调整。我会更新我的答案。
    猜你喜欢
    • 2016-03-06
    • 2023-02-23
    • 1970-01-01
    • 1970-01-01
    • 2015-07-17
    • 2014-01-03
    • 2016-06-02
    • 2013-01-30
    • 1970-01-01
    相关资源
    最近更新 更多