Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[9.x] Added a way to retrieve the first column of the first row from a query #41858

Merged

Conversation

peterlupu
Copy link
Contributor

@peterlupu peterlupu commented Apr 6, 2022

Currently there is no clean way to retrieve the first column of the first row of a more complex raw query.
For example

SELECT COUNT(CASE WHEN food = 'burger' THEN 1 END) FROM menu_items;

The quickest way I know, without using the Query Builder's value() method is:

DB::selectOne("SELECT COUNT(CASE WHEN food = 'burger' THEN 1 END) AS burgers FROM menu_items;")->burgers

This PR adds DB::scalar(), so you can retrieve the result without aliasing the column and referencing the alias:

DB::scalar("SELECT COUNT(CASE WHEN food = 'burger' THEN 1 END) FROM menu_items;")
// returns the count directly

If multiple columns are selected, an exception is thrown (MultipleColumnsSelectedException).

@taylorotwell taylorotwell merged commit 1a43d11 into laravel:9.x Apr 6, 2022
@GrahamCampbell GrahamCampbell changed the title Added a way to retrieve the first column of the first row from a query. [9.x] Added a way to retrieve the first column of the first row from a query Apr 6, 2022
@peterlupu peterlupu deleted the feat/add-connection-query-scalar branch April 6, 2022 21:39
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants