Obtaining SUM('field') in PHP codeField modification using PHPAdd PHP code to block's contentWhy I cannot get translated entitiesObtaining all values from a built formRunning Drupal code inspections via PHP Storm returns incorrect resultsHow do I use PHP code in a block?Programmatically (via php code) create content of a specified typeHaving trouble obtaining a query parameter on a views pageHow can I sum aggregate of expressionSum up views custom text field using aggregation

Terence Tao–type books in other fields?

Replacing tongue and groove floorboards: but can't find a match

Commercial jet accompanied by small plane near Seattle

This message is flooding my syslog, how to find where it comes from?

How can I tell if there was a power cut while I was out?

How did C64 games handle music during gameplay?

A planet illuminated by a black hole?

Are the Cavalier's uses of Unwavering Mark or uses of the bonus attack granted limited per long rest?

What do teaching faculty do during semester breaks?

Send a single HTML email from Thunderbird, overriding the default "plain text" setting

Can I go to the UK from the Schengen on train?

Which Roman general was killed by his own soldiers for not letting them to loot a newly conquered city?

Spoken encryption

Inadvertently nuked my disk permission structure - why?

How to write a sincerely religious protagonist without preaching or affirming or judging their worldview?

Other than a swing wing, what types of variable geometry have flown?

What is the difference between 1/3, 1/2, and full casters?

How do campaign rallies gain candidates votes?

Airplanes in static display at Whiteman AFB

Can two figures have the same area, perimeter, and same number of segments have different shape?

Character is called by their first initial. How do I write it?

Is the "cosmological constant tension" the prime reason that we believe the expansion of the universe is accelerating?

How do I run a game when my PCs have different approaches to combat?

Trapped in an ocean Temple in Minecraft?



Obtaining SUM('field') in PHP code


Field modification using PHPAdd PHP code to block's contentWhy I cannot get translated entitiesObtaining all values from a built formRunning Drupal code inspections via PHP Storm returns incorrect resultsHow do I use PHP code in a block?Programmatically (via php code) create content of a specified typeHaving trouble obtaining a query parameter on a views pageHow can I sum aggregate of expressionSum up views custom text field using aggregation






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








1















Can't figure out how to construct a query to obtain a sum of a field programmatically. The folowing code works fine for counts:



$count = Drupal::entityQuery('node')
->condition('type', 'artefacts')
->condition('status', '1')
->condition('default_langcode', 1)
->condition('field_city', $id)
->count()
->execute();


but no matter how I try I can't figure out how to obtain the sum. There is a lot of examples for Drupal 7 but can't find a single one for Drupal 8.



$sum = Drupal::entityQuery('node')
->condition('type', 'cities')
->condition('status', '1')
->condition('default_langcode', 1)
->condition('field_country', $id)
->aggregate('sum(field_artefact_count)', 'total')
->execute();


seems to return '1' in any circumstances. The documentation on Query class is terse to put it mildly. Apparently execute() is supposed to return an array of entity id's but what's the entity id of a single total of a table of a 1000 records?










share|improve this question






























    1















    Can't figure out how to construct a query to obtain a sum of a field programmatically. The folowing code works fine for counts:



    $count = Drupal::entityQuery('node')
    ->condition('type', 'artefacts')
    ->condition('status', '1')
    ->condition('default_langcode', 1)
    ->condition('field_city', $id)
    ->count()
    ->execute();


    but no matter how I try I can't figure out how to obtain the sum. There is a lot of examples for Drupal 7 but can't find a single one for Drupal 8.



    $sum = Drupal::entityQuery('node')
    ->condition('type', 'cities')
    ->condition('status', '1')
    ->condition('default_langcode', 1)
    ->condition('field_country', $id)
    ->aggregate('sum(field_artefact_count)', 'total')
    ->execute();


    seems to return '1' in any circumstances. The documentation on Query class is terse to put it mildly. Apparently execute() is supposed to return an array of entity id's but what's the entity id of a single total of a table of a 1000 records?










    share|improve this question


























      1












      1








      1








      Can't figure out how to construct a query to obtain a sum of a field programmatically. The folowing code works fine for counts:



      $count = Drupal::entityQuery('node')
      ->condition('type', 'artefacts')
      ->condition('status', '1')
      ->condition('default_langcode', 1)
      ->condition('field_city', $id)
      ->count()
      ->execute();


      but no matter how I try I can't figure out how to obtain the sum. There is a lot of examples for Drupal 7 but can't find a single one for Drupal 8.



      $sum = Drupal::entityQuery('node')
      ->condition('type', 'cities')
      ->condition('status', '1')
      ->condition('default_langcode', 1)
      ->condition('field_country', $id)
      ->aggregate('sum(field_artefact_count)', 'total')
      ->execute();


      seems to return '1' in any circumstances. The documentation on Query class is terse to put it mildly. Apparently execute() is supposed to return an array of entity id's but what's the entity id of a single total of a table of a 1000 records?










      share|improve this question
















      Can't figure out how to construct a query to obtain a sum of a field programmatically. The folowing code works fine for counts:



      $count = Drupal::entityQuery('node')
      ->condition('type', 'artefacts')
      ->condition('status', '1')
      ->condition('default_langcode', 1)
      ->condition('field_city', $id)
      ->count()
      ->execute();


      but no matter how I try I can't figure out how to obtain the sum. There is a lot of examples for Drupal 7 but can't find a single one for Drupal 8.



      $sum = Drupal::entityQuery('node')
      ->condition('type', 'cities')
      ->condition('status', '1')
      ->condition('default_langcode', 1)
      ->condition('field_country', $id)
      ->aggregate('sum(field_artefact_count)', 'total')
      ->execute();


      seems to return '1' in any circumstances. The documentation on Query class is terse to put it mildly. Apparently execute() is supposed to return an array of entity id's but what's the entity id of a single total of a table of a 1000 records?







      8






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Jul 16 at 6:26









      kiamlaluno

      81.6k10 gold badges136 silver badges252 bronze badges




      81.6k10 gold badges136 silver badges252 bronze badges










      asked Jul 16 at 6:15









      MarassaMarassa

      337 bronze badges




      337 bronze badges




















          1 Answer
          1






          active

          oldest

          votes


















          3














          Use QueryAggregateInterface::execute:



          $result = Drupal::entityQueryAggregate('node')
          ->aggregate('nid', 'sum')
          ->condition('status', NodeInterface::PUBLISHED)
          ->execute();


          The result returned is keyed by fieldname and aggregate function:



          $sum = $result['0']['nid_sum'];





          share|improve this answer

























          • Wow, thanks a ton! Now the only question remaining is how I could possibly find it unless I knew the exact class/interface name beforehand ;) No combination of Drupal 8 / query / aggregate / total / sum would bring it up on google...

            – Marassa
            Jul 16 at 7:19













          Your Answer








          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "220"
          ;
          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: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          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%2fdrupal.stackexchange.com%2fquestions%2f283506%2fobtaining-sumfield-in-php-code%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          3














          Use QueryAggregateInterface::execute:



          $result = Drupal::entityQueryAggregate('node')
          ->aggregate('nid', 'sum')
          ->condition('status', NodeInterface::PUBLISHED)
          ->execute();


          The result returned is keyed by fieldname and aggregate function:



          $sum = $result['0']['nid_sum'];





          share|improve this answer

























          • Wow, thanks a ton! Now the only question remaining is how I could possibly find it unless I knew the exact class/interface name beforehand ;) No combination of Drupal 8 / query / aggregate / total / sum would bring it up on google...

            – Marassa
            Jul 16 at 7:19















          3














          Use QueryAggregateInterface::execute:



          $result = Drupal::entityQueryAggregate('node')
          ->aggregate('nid', 'sum')
          ->condition('status', NodeInterface::PUBLISHED)
          ->execute();


          The result returned is keyed by fieldname and aggregate function:



          $sum = $result['0']['nid_sum'];





          share|improve this answer

























          • Wow, thanks a ton! Now the only question remaining is how I could possibly find it unless I knew the exact class/interface name beforehand ;) No combination of Drupal 8 / query / aggregate / total / sum would bring it up on google...

            – Marassa
            Jul 16 at 7:19













          3












          3








          3







          Use QueryAggregateInterface::execute:



          $result = Drupal::entityQueryAggregate('node')
          ->aggregate('nid', 'sum')
          ->condition('status', NodeInterface::PUBLISHED)
          ->execute();


          The result returned is keyed by fieldname and aggregate function:



          $sum = $result['0']['nid_sum'];





          share|improve this answer















          Use QueryAggregateInterface::execute:



          $result = Drupal::entityQueryAggregate('node')
          ->aggregate('nid', 'sum')
          ->condition('status', NodeInterface::PUBLISHED)
          ->execute();


          The result returned is keyed by fieldname and aggregate function:



          $sum = $result['0']['nid_sum'];






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Jul 16 at 9:22









          ya.teck

          3,9213 gold badges24 silver badges37 bronze badges




          3,9213 gold badges24 silver badges37 bronze badges










          answered Jul 16 at 6:33









          4k44k4

          56.5k5 gold badges71 silver badges115 bronze badges




          56.5k5 gold badges71 silver badges115 bronze badges












          • Wow, thanks a ton! Now the only question remaining is how I could possibly find it unless I knew the exact class/interface name beforehand ;) No combination of Drupal 8 / query / aggregate / total / sum would bring it up on google...

            – Marassa
            Jul 16 at 7:19

















          • Wow, thanks a ton! Now the only question remaining is how I could possibly find it unless I knew the exact class/interface name beforehand ;) No combination of Drupal 8 / query / aggregate / total / sum would bring it up on google...

            – Marassa
            Jul 16 at 7:19
















          Wow, thanks a ton! Now the only question remaining is how I could possibly find it unless I knew the exact class/interface name beforehand ;) No combination of Drupal 8 / query / aggregate / total / sum would bring it up on google...

          – Marassa
          Jul 16 at 7:19





          Wow, thanks a ton! Now the only question remaining is how I could possibly find it unless I knew the exact class/interface name beforehand ;) No combination of Drupal 8 / query / aggregate / total / sum would bring it up on google...

          – Marassa
          Jul 16 at 7:19

















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Drupal Answers!


          • 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%2fdrupal.stackexchange.com%2fquestions%2f283506%2fobtaining-sumfield-in-php-code%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

          Grendel Contents Story Scholarship Depictions Notes References Navigation menu10.1093/notesj/gjn112Berserkeree

          Area configuration aggregation error after install Porto themeMagento 2.1 CE Installed but front/backend not loading/workingCSS not loading on page within Magento 2 pageCannot install module in Magento 2no commands defined in the “setup” namespace. in Magento2Magento 2: Static files are present but shows 404Why do i have to always run the commands to clean cache in Magento 2.1.8?Failure reason: 'Unable to unserialize value.'Error 500 after magento migrationIn production mode the site does not loadMagento 2 : Error 500 after installing

          Middle Expansion Olielle Resaix Definition: Uttering songs of triumph shouting with joy triumphant exulting Sejunction Journal 붙다 달 고급 품목 외출 The stretch trades the screeching tin. Definition: The act of speaking with a drawl a drawl Cough Sand Definition: An uproar a quarrel a noisy outbreak Shake Iron Publicize Horse House Baby 사과 Resaix Flaggy Jelly Temporary Unequaled Puppet A drop in the bucket Shrew 성격 회원 성질 미팅 The burn frames the tacky quality. Materialistic The smoke reduces the way. Yammoe Nondescript Cheek 얼굴 배 약하다 날리다 타다 The illegal country shows the iron. Help Rule Drearien Smoke Teaching Meaty Wasp Abraham Lincoln Jaws 진심 수리하다 Size Cork Idea Convert Think Lark John Lennon 거울 청소 군 추천하다 아이스크림