默认情况下,Laravel模型组

时间:2019-09-11 19:42:36

标签: laravel collections eloquent model lumen

我有一个使用雄辩的Laravel应用程序,该应用程序按预期返回了包含价格和其他信息的报价。我想知道的是,有一种方法可以在调用模型的每个实例中应用GroupBy。

在这种情况下,我有价格:

In [5]: df['Cases'] = df.Cases[::-1].cumsum()

In [6]: df
Out[6]:
        Month  Cases
0  2019-06-01      3
1  2019-05-01      2
2  2019-04-01      2
3  2019-03-01      2
4  2019-02-01      0

我想显示以下内容:

{
    [
        {'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 :: with('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}
        ]
}

但想得到:

{
    "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}
           ]
        }
}

调用此模型还有许多其他复杂的关系,因此不幸的是,不仅仅是使用该模型时在控制器中创建分组依据的情况,它确实需要成为该模型的默认操作模式。模型。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

也许您可以尝试:

$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

相关问题