Laravel Convert Raw Query Containing 'as' Keyword to Eloquent

Majid Alaeinia :

I have this raw query:

SELECT business_id, count(*) as how_many from dbname.gateway_transactions WHERE DATE(created_at) = '2020-02-02' group by business_id order by how_many desc limit 5

And this is the result:

enter image description here

I want to have the result of this query (the content of the image), as an array. How can I do this?

I have used this:

$a = GatewayTransaction::selectRaw("SELECT business_id, count(*) as how_many from dbname.gateway_transactions WHERE DATE(created_at) = '2020-02-02' group by business_id order by how_many desc limit 5");

But not able to get what I need. I need such an array just like the image above:

[
51  => 725,
176 => 405,
229 => 264,
98  => 109,
136 => 92
]
TsaiKoga :

You need to use Eloquent builder like this:

$a = GatewayTransaction::selectRaw('business_id, count(*) as how_many')
                       ->whereDate('created_at', '2020-02-02')
                       ->groupBy('business_id')
                       ->orderBy('how_many', 'desc')
                       ->take(5)
                       ->get();

Guess you like

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