Laravel different selects in one query2019 Community Moderator ElectionHow to output MySQL query results in CSV format?What's the difference between utf8_general_ci and utf8_unicode_ciWhat's the difference between INNER JOIN, LEFT JOIN, RIGHT JOIN and FULL JOIN?Laravel 4 Eloquent Query Using WHERE with OR AND OR?How to Create Multiple Where Clause Query Using Laravel Eloquent?Laravel Eloquent get results grouped by daysONE SQL query to count records on different conditionsLaravel Query builder - query not working but works in SQL consoleLaravel : Select and GroupBy SQL Query Error. Multiple Selects with groupBy? Is it Possible?Laravel pagination for GROUPED queries

Inhabiting Mars versus going straight for a Dyson swarm

Variable completely messes up echoed string

Generic TVP tradeoffs?

What favor did Moody owe Dumbledore?

Knife as defense against stray dogs

Asserting that Atheism and Theism are both faith based positions

Do native speakers use "ultima" and "proxima" frequently in spoken English?

Why is there so much iron?

Synchronized implementation of a bank account in Java

Is it possible to stack the damage done by the Absorb Elements spell?

gerund and noun applications

How does 取材で訪れた integrate into this sentence?

Writing in a Christian voice

Optimising a list searching algorithm

If "dar" means "to give", what does "daros" mean?

Help rendering a complicated sum/product formula

Violin - Can double stops be played when the strings are not next to each other?

How to terminate ping <dest> &

What (if any) is the reason to buy in small local stores?

What exactly term 'companion plants' means?

How to define limit operations in general topological spaces? Are nets able to do this?

Does the attack bonus from a Masterwork weapon stack with the attack bonus from Masterwork ammunition?

Calculate the frequency of characters in a string

How do hiring committees for research positions view getting "scooped"?



Laravel different selects in one query



2019 Community Moderator ElectionHow to output MySQL query results in CSV format?What's the difference between utf8_general_ci and utf8_unicode_ciWhat's the difference between INNER JOIN, LEFT JOIN, RIGHT JOIN and FULL JOIN?Laravel 4 Eloquent Query Using WHERE with OR AND OR?How to Create Multiple Where Clause Query Using Laravel Eloquent?Laravel Eloquent get results grouped by daysONE SQL query to count records on different conditionsLaravel Query builder - query not working but works in SQL consoleLaravel : Select and GroupBy SQL Query Error. Multiple Selects with groupBy? Is it Possible?Laravel pagination for GROUPED queries










0















I will try to describe my situation; I have two separate queries below:



 public function getDriversCount($request) 
return Driver::count();



and the second one:



public function getDriversCountWithStatus($request) 
return Driver::select('status', DB::raw('count(*) as total'))
->groupBy('status')
->get();



now we can see that these two are two separate functions and to separate queries. In the first one I am counting the whole drivers table records, but in the second one I am counting according to status groups. So how can I achieve the same result by one function and one query? something like that:




"absolute_total": 21,
"with_status": [

"status": 0,
"total": 11
,

"status": 1,
"total": 10

]



this one I received manually by calling these two functions separately.










share|improve this question
























  • Stricktly speaking, you cannot get both counts in one query. You can combine the two with subqueries and union into one, but it is not going to be very efficient. Technically, you can do the count by status as a single query, then add up the subcounts to get the total count in php.

    – Shadow
    Mar 6 at 22:46















0















I will try to describe my situation; I have two separate queries below:



 public function getDriversCount($request) 
return Driver::count();



and the second one:



public function getDriversCountWithStatus($request) 
return Driver::select('status', DB::raw('count(*) as total'))
->groupBy('status')
->get();



now we can see that these two are two separate functions and to separate queries. In the first one I am counting the whole drivers table records, but in the second one I am counting according to status groups. So how can I achieve the same result by one function and one query? something like that:




"absolute_total": 21,
"with_status": [

"status": 0,
"total": 11
,

"status": 1,
"total": 10

]



this one I received manually by calling these two functions separately.










share|improve this question
























  • Stricktly speaking, you cannot get both counts in one query. You can combine the two with subqueries and union into one, but it is not going to be very efficient. Technically, you can do the count by status as a single query, then add up the subcounts to get the total count in php.

    – Shadow
    Mar 6 at 22:46













0












0








0








I will try to describe my situation; I have two separate queries below:



 public function getDriversCount($request) 
return Driver::count();



and the second one:



public function getDriversCountWithStatus($request) 
return Driver::select('status', DB::raw('count(*) as total'))
->groupBy('status')
->get();



now we can see that these two are two separate functions and to separate queries. In the first one I am counting the whole drivers table records, but in the second one I am counting according to status groups. So how can I achieve the same result by one function and one query? something like that:




"absolute_total": 21,
"with_status": [

"status": 0,
"total": 11
,

"status": 1,
"total": 10

]



this one I received manually by calling these two functions separately.










share|improve this question
















I will try to describe my situation; I have two separate queries below:



 public function getDriversCount($request) 
return Driver::count();



and the second one:



public function getDriversCountWithStatus($request) 
return Driver::select('status', DB::raw('count(*) as total'))
->groupBy('status')
->get();



now we can see that these two are two separate functions and to separate queries. In the first one I am counting the whole drivers table records, but in the second one I am counting according to status groups. So how can I achieve the same result by one function and one query? something like that:




"absolute_total": 21,
"with_status": [

"status": 0,
"total": 11
,

"status": 1,
"total": 10

]



this one I received manually by calling these two functions separately.







php mysql laravel eloquent






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 6 at 22:27









Taplar

17.1k21529




17.1k21529










asked Mar 6 at 22:09









O. ShekriladzeO. Shekriladze

1799




1799












  • Stricktly speaking, you cannot get both counts in one query. You can combine the two with subqueries and union into one, but it is not going to be very efficient. Technically, you can do the count by status as a single query, then add up the subcounts to get the total count in php.

    – Shadow
    Mar 6 at 22:46

















  • Stricktly speaking, you cannot get both counts in one query. You can combine the two with subqueries and union into one, but it is not going to be very efficient. Technically, you can do the count by status as a single query, then add up the subcounts to get the total count in php.

    – Shadow
    Mar 6 at 22:46
















Stricktly speaking, you cannot get both counts in one query. You can combine the two with subqueries and union into one, but it is not going to be very efficient. Technically, you can do the count by status as a single query, then add up the subcounts to get the total count in php.

– Shadow
Mar 6 at 22:46





Stricktly speaking, you cannot get both counts in one query. You can combine the two with subqueries and union into one, but it is not going to be very efficient. Technically, you can do the count by status as a single query, then add up the subcounts to get the total count in php.

– Shadow
Mar 6 at 22:46












2 Answers
2






active

oldest

votes


















0














You can do the below, we set an empty array at the start, so if the function returns an empty array you can do further checking on that:



public function getDriversCountAndStatus($request)

// Set the array that will be returned
$driversCountWithStatus = [];

// Get the driver count
$driverCount = Driver::count();

// Get the driver status
$driverStatus = Driver::select('status', DB::raw('count(*) as total'))
->groupBy('status')
->get();

// Combine the driver count and status into one array
$driversCountWithStatus = [
"absolute_total" => $driverCount,
"with_status" => $driverStatus;
];

return $driversCountWithStatus;






share|improve this answer























  • He wants to do just one query, i don't think your answer will help OP.

    – Lucas Piazzi
    Mar 6 at 22:23











  • I read it as he wants one function, but if he wants one query, then I can update above, we'll see what he says

    – giolliano sulit
    Mar 6 at 22:24


















0














I can't comment yet because I don't have enough rep.



I think I understand what you mean. The easiest way to do this would be chaining a couple of selects together.



Something like



public function getDriversCountWithStatus($request) 
return Driver::select('total', DB::raw('count(*) as total'))
->addSelect('status', DB::raw('count(*) as total group by status'))
->get();






share|improve this answer























  • This is still not going to be one query...

    – Shadow
    Mar 6 at 22:44











  • No but I'm not sure there's a method for doing it in one statement. Unless he tries PDO?

    – stokoe0990
    Mar 6 at 23:02











  • Via raw sql query with union...

    – Shadow
    Mar 6 at 23:38










Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55032967%2flaravel-different-selects-in-one-query%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























2 Answers
2






active

oldest

votes








2 Answers
2






active

oldest

votes









active

oldest

votes






active

oldest

votes









0














You can do the below, we set an empty array at the start, so if the function returns an empty array you can do further checking on that:



public function getDriversCountAndStatus($request)

// Set the array that will be returned
$driversCountWithStatus = [];

// Get the driver count
$driverCount = Driver::count();

// Get the driver status
$driverStatus = Driver::select('status', DB::raw('count(*) as total'))
->groupBy('status')
->get();

// Combine the driver count and status into one array
$driversCountWithStatus = [
"absolute_total" => $driverCount,
"with_status" => $driverStatus;
];

return $driversCountWithStatus;






share|improve this answer























  • He wants to do just one query, i don't think your answer will help OP.

    – Lucas Piazzi
    Mar 6 at 22:23











  • I read it as he wants one function, but if he wants one query, then I can update above, we'll see what he says

    – giolliano sulit
    Mar 6 at 22:24















0














You can do the below, we set an empty array at the start, so if the function returns an empty array you can do further checking on that:



public function getDriversCountAndStatus($request)

// Set the array that will be returned
$driversCountWithStatus = [];

// Get the driver count
$driverCount = Driver::count();

// Get the driver status
$driverStatus = Driver::select('status', DB::raw('count(*) as total'))
->groupBy('status')
->get();

// Combine the driver count and status into one array
$driversCountWithStatus = [
"absolute_total" => $driverCount,
"with_status" => $driverStatus;
];

return $driversCountWithStatus;






share|improve this answer























  • He wants to do just one query, i don't think your answer will help OP.

    – Lucas Piazzi
    Mar 6 at 22:23











  • I read it as he wants one function, but if he wants one query, then I can update above, we'll see what he says

    – giolliano sulit
    Mar 6 at 22:24













0












0








0







You can do the below, we set an empty array at the start, so if the function returns an empty array you can do further checking on that:



public function getDriversCountAndStatus($request)

// Set the array that will be returned
$driversCountWithStatus = [];

// Get the driver count
$driverCount = Driver::count();

// Get the driver status
$driverStatus = Driver::select('status', DB::raw('count(*) as total'))
->groupBy('status')
->get();

// Combine the driver count and status into one array
$driversCountWithStatus = [
"absolute_total" => $driverCount,
"with_status" => $driverStatus;
];

return $driversCountWithStatus;






share|improve this answer













You can do the below, we set an empty array at the start, so if the function returns an empty array you can do further checking on that:



public function getDriversCountAndStatus($request)

// Set the array that will be returned
$driversCountWithStatus = [];

// Get the driver count
$driverCount = Driver::count();

// Get the driver status
$driverStatus = Driver::select('status', DB::raw('count(*) as total'))
->groupBy('status')
->get();

// Combine the driver count and status into one array
$driversCountWithStatus = [
"absolute_total" => $driverCount,
"with_status" => $driverStatus;
];

return $driversCountWithStatus;







share|improve this answer












share|improve this answer



share|improve this answer










answered Mar 6 at 22:21









giolliano sulitgiolliano sulit

780511




780511












  • He wants to do just one query, i don't think your answer will help OP.

    – Lucas Piazzi
    Mar 6 at 22:23











  • I read it as he wants one function, but if he wants one query, then I can update above, we'll see what he says

    – giolliano sulit
    Mar 6 at 22:24

















  • He wants to do just one query, i don't think your answer will help OP.

    – Lucas Piazzi
    Mar 6 at 22:23











  • I read it as he wants one function, but if he wants one query, then I can update above, we'll see what he says

    – giolliano sulit
    Mar 6 at 22:24
















He wants to do just one query, i don't think your answer will help OP.

– Lucas Piazzi
Mar 6 at 22:23





He wants to do just one query, i don't think your answer will help OP.

– Lucas Piazzi
Mar 6 at 22:23













I read it as he wants one function, but if he wants one query, then I can update above, we'll see what he says

– giolliano sulit
Mar 6 at 22:24





I read it as he wants one function, but if he wants one query, then I can update above, we'll see what he says

– giolliano sulit
Mar 6 at 22:24













0














I can't comment yet because I don't have enough rep.



I think I understand what you mean. The easiest way to do this would be chaining a couple of selects together.



Something like



public function getDriversCountWithStatus($request) 
return Driver::select('total', DB::raw('count(*) as total'))
->addSelect('status', DB::raw('count(*) as total group by status'))
->get();






share|improve this answer























  • This is still not going to be one query...

    – Shadow
    Mar 6 at 22:44











  • No but I'm not sure there's a method for doing it in one statement. Unless he tries PDO?

    – stokoe0990
    Mar 6 at 23:02











  • Via raw sql query with union...

    – Shadow
    Mar 6 at 23:38















0














I can't comment yet because I don't have enough rep.



I think I understand what you mean. The easiest way to do this would be chaining a couple of selects together.



Something like



public function getDriversCountWithStatus($request) 
return Driver::select('total', DB::raw('count(*) as total'))
->addSelect('status', DB::raw('count(*) as total group by status'))
->get();






share|improve this answer























  • This is still not going to be one query...

    – Shadow
    Mar 6 at 22:44











  • No but I'm not sure there's a method for doing it in one statement. Unless he tries PDO?

    – stokoe0990
    Mar 6 at 23:02











  • Via raw sql query with union...

    – Shadow
    Mar 6 at 23:38













0












0








0







I can't comment yet because I don't have enough rep.



I think I understand what you mean. The easiest way to do this would be chaining a couple of selects together.



Something like



public function getDriversCountWithStatus($request) 
return Driver::select('total', DB::raw('count(*) as total'))
->addSelect('status', DB::raw('count(*) as total group by status'))
->get();






share|improve this answer













I can't comment yet because I don't have enough rep.



I think I understand what you mean. The easiest way to do this would be chaining a couple of selects together.



Something like



public function getDriversCountWithStatus($request) 
return Driver::select('total', DB::raw('count(*) as total'))
->addSelect('status', DB::raw('count(*) as total group by status'))
->get();







share|improve this answer












share|improve this answer



share|improve this answer










answered Mar 6 at 22:37









stokoe0990stokoe0990

437




437












  • This is still not going to be one query...

    – Shadow
    Mar 6 at 22:44











  • No but I'm not sure there's a method for doing it in one statement. Unless he tries PDO?

    – stokoe0990
    Mar 6 at 23:02











  • Via raw sql query with union...

    – Shadow
    Mar 6 at 23:38

















  • This is still not going to be one query...

    – Shadow
    Mar 6 at 22:44











  • No but I'm not sure there's a method for doing it in one statement. Unless he tries PDO?

    – stokoe0990
    Mar 6 at 23:02











  • Via raw sql query with union...

    – Shadow
    Mar 6 at 23:38
















This is still not going to be one query...

– Shadow
Mar 6 at 22:44





This is still not going to be one query...

– Shadow
Mar 6 at 22:44













No but I'm not sure there's a method for doing it in one statement. Unless he tries PDO?

– stokoe0990
Mar 6 at 23:02





No but I'm not sure there's a method for doing it in one statement. Unless he tries PDO?

– stokoe0990
Mar 6 at 23:02













Via raw sql query with union...

– Shadow
Mar 6 at 23:38





Via raw sql query with union...

– Shadow
Mar 6 at 23:38

















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55032967%2flaravel-different-selects-in-one-query%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Save data to MySQL database using ExtJS and PHP [closed]2019 Community Moderator ElectionHow can I prevent SQL injection in PHP?Which MySQL data type to use for storing boolean valuesPHP: Delete an element from an arrayHow do I connect to a MySQL Database in Python?Should I use the datetime or timestamp data type in MySQL?How to get a list of MySQL user accountsHow Do You Parse and Process HTML/XML in PHP?Reference — What does this symbol mean in PHP?How does PHP 'foreach' actually work?Why shouldn't I use mysql_* functions in PHP?

Compiling GNU Global with universal-ctags support Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!Tags for Emacs: Relationship between etags, ebrowse, cscope, GNU Global and exuberant ctagsVim and Ctags tips and trickscscope or ctags why choose one over the other?scons and ctagsctags cannot open option file “.ctags”Adding tag scopes in universal-ctagsShould I use Universal-ctags?Universal ctags on WindowsHow do I install GNU Global with universal ctags support using Homebrew?Universal ctags with emacsHow to highlight ctags generated by Universal Ctags in Vim?

Add ONERROR event to image from jsp tldHow to add an image to a JPanel?Saving image from PHP URLHTML img scalingCheck if an image is loaded (no errors) with jQueryHow to force an <img> to take up width, even if the image is not loadedHow do I populate hidden form field with a value set in Spring ControllerStyling Raw elements Generated from JSP tagds with Jquery MobileLimit resizing of images with explicitly set width and height attributeserror TLD use in a jsp fileJsp tld files cannot be resolved