Combine query results in Eloquent, keyed by one of the columns

jovan :

I have a MySQL table called stock_history that looks something like this:

id | date       | mnemonic      | value
---------------------------------------
1  | 2020-01-21 | IQ_CLOSEPRICE | 147.15
2  | 2020-01-22 | IQ_CLOSEPRICE | 149.31
3  | 2020-01-23 | IQ_CLOSEPRICE | 150.11
4  | 2020-01-21 | IQ_TRADES     | 323
5  | 2020-01-22 | IQ_TRADES     | 542
6  | 2020-01-22 | IQ_TRADES     | 712
7  | 2020-01-21 | IQ_PAYOUTS    | 23

Is it possible to build a query that would return IQ_CLOSEPRICE and IQ_TRADES rows for a range of dates, keyed by date?

For example, if I want to get IQ_CLOSEPRICE and IQ_TRADES for the range 2020-01-21 to 2020-01-22, it should return something like:

[
    '2020-01-21' => [
        'IQ_CLOSEPRICE' => 147.15,
        'IQ_TRADES' => 323
    ],
    '2020-01-22' => [
        'IQ_CLOSEPRICE' => 149.31,
        'IQ_TRADES' => 542
    ],
]

Of course, it is easy to return the data in its natural structure, like:

StockHistory::where('date', '>=', '2020-01-21')
    ->where('date', '<=', '2020-01-22')
    ->whereIn('mnemonic', ('IQ_CLOSEPRICE', 'IQ_TRADES')
    ->get();

But, I would like Eloquent to return the above structure to save me from looping through the whole list after receiving the query results, if possible. If not, then we can do without keying by date, but it would be great to at least put IQ_CLOSEPRICE and IQ_TRADES in the same array element, like:

[
    [
        'IQ_CLOSEPRICE' => 147.15,
        'IQ_TRADES' => 323,
        'date' => '2020-01-21'
    ],
    [
        'IQ_CLOSEPRICE' => 149.31,
        'IQ_TRADES' => 542
        'date' => '2020-01-22'
    ],
]
TsaiKoga :

Firstly, something wrong with the code whereIn, try to use array:

->whereIn('mnemonic', ['IQ_CLOSEPRICE', 'IQ_TRADES'])

Secondly you can use collection's groupBy to group these datas with date:

->get()->groupBy('date');

Thirdly, the value 'IQ_CLOSEPRICE', 'IQ_TRADES' is not the column name of stock_history, there are columns mnemonic's values. If you want to get them as key, you can use pluck like this, the mnemonic's value will be the key, and the value's value will be the value:

->pluck('value', 'mnemonic'); // return ['IQ_CLOSEPRICE' => 147.15,...]

So your code need to look like this:

StockHistory::where('date', '>=', '2020-01-21')
    ->where('date', '<=', '2020-01-22')
    ->whereIn('mnemonic', ['IQ_CLOSEPRICE', 'IQ_TRADES'])
    ->get()
    ->groupBy('date')
    ->map(function($item) {
        return $item->pluck('value', 'mnemonic');
    })->toArray();

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=13981&siteId=1