laravel - 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');
}
}
任何帮助是极大的赞赏!
解决方案
您可以使用 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';
});
推荐阅读
- url - 我需要 Plugin Audio 来支持 Android、iOS 的颤振工作
- react-native - 在录制视频时处理相机翻转而不停止它反应原生
- powershell - 声明变量时在powershell中抑制不需要的输出
- c++ - 交叉编译后 cURL HTTPS 不起作用
- javascript - 如何从 axios 响应对象中的所有项目中提取特定值到 aa vuex 状态
- javascript - Material Design - Confirmation Dialog - 如何在 dialog.listen 方法中使用 Promise?
- django - 带参数的Django调用命令
- ssh - 如何使用两个代理通过 ssh 进行端口转发?
- python - 基本计算器的python中elif的语法错误
- swift - 在swift 5中创建一个mysql连接函数