laravel - Laravel 模型组默认
问题描述
我有一个使用 eloquent 的 Laravel 应用程序,它按预期返回带有价格和其他信息的报价。我想知道的是,有没有一种方法可以在调用模型的每个实例中应用 GroupBy。
在这种情况下,我有价格:
{
[
{'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}
]
}
但这将适用于调用模型的所有实例。因此,此时调用与价格关系的报价 (Offer::with('prices')) 得到:
{
"offer":
{
"name": 'test',
"description": 'tester',
"prices":
[
{'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}
]
}
}
但想得到:
{
"offer":
{
"name": 'test',
"description": 'tester',
"prices":
[
{
"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}
]
}
]
}
}
调用此模型时还有许多其他复杂的关系,因此不幸的是,它不仅仅是在使用模型时在控制器中创建 group by 的情况,它确实需要成为模型的默认操作模式。任何帮助是极大的赞赏。
解决方案
也许你可以试试:
$myCollection='yousearch';
$personal= $myCollection->where('personal',1)->all();
$business= $myCollection->where('busines',1)->all();
$myNewCollection=array('personal'=$personal, 'business'=$business);
我相信它可以改进,在任何情况下你都可以应用一些方法来处理集合:检查https://laravel.com/docs/5.8/collections
推荐阅读
- c++ - 从 ANSI 字符串转换为 std::basic_string 的正确函数声明
- php - how to solve header location warning wordpress
- haskell - Compile Haskell programs to LLVM IR
- jira - 如何在 JIRA 中将发布设置为“已发布”
- android - 如何使用改造从 GET url 获取响应
- javascript - Is it necessary to wrap a promise in a function?
- android - Adding Name and Image at the bottom of Opentok Publisher's Stream and It should be visible on the Subscriber's end by default
- reactjs - How to set TextField to empty string?
- r - Convert dates from XLS into R
- discord - How to mention mentioned users in a message?