Group and count on related modelCakePHP: Load count of related Models with bindModelLaravel 4 distant Eloquent relationsLaravel group by belongstoEloquent: Distinct values and counts from relationsRetrieve distant relation through has-many-through for many-to-many relation in LaravelLaravel Model: how to get all relations as array with custom array keys?Laravel collection group byLoad laravel eloquent model withCount of related modelRetrieve related models using hasManyThrough on a pivot table - Laravel 5.7Laravel 5.6 / Eloquent Sum and GroupBy with related tables/relationships

How to get the speed of my spaceship?

What is this airplane with small wings at different angles seen at Paphos Airport?

Did William Shakespeare hide things in his writings?

Implicit conversion between decimals with different precisions

How predictable is $RANDOM really?

Passwordless authentication - how invalidate login code

Better random (unique) file name

As a supervisor, what feedback would you expect from a PhD who quits?

Bringing coumarin-containing liquor into the USA

Groups where no elements commute except for the trivial cases

Is there a standard definition of the "stall" phenomena?

Why does "sattsehen" take accusative "mich", not dative "mir"? Even though it is not "me" that I'm looking at?

Any way to meet code with 40.7% or 40.44% conduit fill?

Is conquering your neighbors to fight a greater enemy a valid strategy?

Gory anime with pink haired girl escaping an asylum

Does the sensor of a dslr count the number of photons that hits it?

PhD: When to quit and move on?

How important is it for multiple POVs to run chronologically?

What's the difference between a type and a kind?

Howto display unicode character u2026 in terminal mode in emacs

How can I use my cell phone's light as a reading light?

Minor differences between two recorded guitars

What is the meaning of "prairie-dog" in this sentence?

Is it acceptable that I plot a time-series figure with years increasing from right to left?



Group and count on related model


CakePHP: Load count of related Models with bindModelLaravel 4 distant Eloquent relationsLaravel group by belongstoEloquent: Distinct values and counts from relationsRetrieve distant relation through has-many-through for many-to-many relation in LaravelLaravel Model: how to get all relations as array with custom array keys?Laravel collection group byLoad laravel eloquent model withCount of related modelRetrieve related models using hasManyThrough on a pivot table - Laravel 5.7Laravel 5.6 / Eloquent Sum and GroupBy with related tables/relationships






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








0















I have a table called item that has a belongsTo relationship with a table called source. I want to group all items by their source and in the end I want an array that has source->name as the key and number of related items as the value.



This is what I've got so far:



Item::where('type', '=', Item::TYPE_POST)
->with('source')
->select('source_id', DB::raw('count(*) as total'))
->groupBy('source_id')
->pluck('total', 'source_id')
->all();


array:1 [
89 => 149
]


This gives me the structure that I want, but the items aren't grouped by source->name but by source_id which is a field in the Item table. Is there a way to get the key in the array to be a field from the related table?










share|improve this question




























    0















    I have a table called item that has a belongsTo relationship with a table called source. I want to group all items by their source and in the end I want an array that has source->name as the key and number of related items as the value.



    This is what I've got so far:



    Item::where('type', '=', Item::TYPE_POST)
    ->with('source')
    ->select('source_id', DB::raw('count(*) as total'))
    ->groupBy('source_id')
    ->pluck('total', 'source_id')
    ->all();


    array:1 [
    89 => 149
    ]


    This gives me the structure that I want, but the items aren't grouped by source->name but by source_id which is a field in the Item table. Is there a way to get the key in the array to be a field from the related table?










    share|improve this question
























      0












      0








      0








      I have a table called item that has a belongsTo relationship with a table called source. I want to group all items by their source and in the end I want an array that has source->name as the key and number of related items as the value.



      This is what I've got so far:



      Item::where('type', '=', Item::TYPE_POST)
      ->with('source')
      ->select('source_id', DB::raw('count(*) as total'))
      ->groupBy('source_id')
      ->pluck('total', 'source_id')
      ->all();


      array:1 [
      89 => 149
      ]


      This gives me the structure that I want, but the items aren't grouped by source->name but by source_id which is a field in the Item table. Is there a way to get the key in the array to be a field from the related table?










      share|improve this question














      I have a table called item that has a belongsTo relationship with a table called source. I want to group all items by their source and in the end I want an array that has source->name as the key and number of related items as the value.



      This is what I've got so far:



      Item::where('type', '=', Item::TYPE_POST)
      ->with('source')
      ->select('source_id', DB::raw('count(*) as total'))
      ->groupBy('source_id')
      ->pluck('total', 'source_id')
      ->all();


      array:1 [
      89 => 149
      ]


      This gives me the structure that I want, but the items aren't grouped by source->name but by source_id which is a field in the Item table. Is there a way to get the key in the array to be a field from the related table?







      php laravel eloquent






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Mar 25 at 20:29









      MalaMala

      255 bronze badges




      255 bronze badges






















          1 Answer
          1






          active

          oldest

          votes


















          0














          I haven't tried these but it should get you close anyways



          Using Collections



          Item::where('type', '=', Item::TYPE_POST)
          ->with('source.name')
          ->get()
          ->mapWithKeys(function ($item)
          return [$item->service->name => $item];
          )
          ->map(function ($items, $name)
          return [
          $name => $items->count()
          ];
          );


          Using Query



          DB::table('items')
          ->selectRaw('sources.name as name, count(*.items) as count')
          ->join('sources', 'sources.id', 'items.source_id')
          ->where('type', '=', Item::TYPE_POST)
          ->groupBy('sources.id')
          ->get()
          ->pluck('count', 'name')





          share|improve this answer






















            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%2f55345927%2fgroup-and-count-on-related-model%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









            0














            I haven't tried these but it should get you close anyways



            Using Collections



            Item::where('type', '=', Item::TYPE_POST)
            ->with('source.name')
            ->get()
            ->mapWithKeys(function ($item)
            return [$item->service->name => $item];
            )
            ->map(function ($items, $name)
            return [
            $name => $items->count()
            ];
            );


            Using Query



            DB::table('items')
            ->selectRaw('sources.name as name, count(*.items) as count')
            ->join('sources', 'sources.id', 'items.source_id')
            ->where('type', '=', Item::TYPE_POST)
            ->groupBy('sources.id')
            ->get()
            ->pluck('count', 'name')





            share|improve this answer



























              0














              I haven't tried these but it should get you close anyways



              Using Collections



              Item::where('type', '=', Item::TYPE_POST)
              ->with('source.name')
              ->get()
              ->mapWithKeys(function ($item)
              return [$item->service->name => $item];
              )
              ->map(function ($items, $name)
              return [
              $name => $items->count()
              ];
              );


              Using Query



              DB::table('items')
              ->selectRaw('sources.name as name, count(*.items) as count')
              ->join('sources', 'sources.id', 'items.source_id')
              ->where('type', '=', Item::TYPE_POST)
              ->groupBy('sources.id')
              ->get()
              ->pluck('count', 'name')





              share|improve this answer

























                0












                0








                0







                I haven't tried these but it should get you close anyways



                Using Collections



                Item::where('type', '=', Item::TYPE_POST)
                ->with('source.name')
                ->get()
                ->mapWithKeys(function ($item)
                return [$item->service->name => $item];
                )
                ->map(function ($items, $name)
                return [
                $name => $items->count()
                ];
                );


                Using Query



                DB::table('items')
                ->selectRaw('sources.name as name, count(*.items) as count')
                ->join('sources', 'sources.id', 'items.source_id')
                ->where('type', '=', Item::TYPE_POST)
                ->groupBy('sources.id')
                ->get()
                ->pluck('count', 'name')





                share|improve this answer













                I haven't tried these but it should get you close anyways



                Using Collections



                Item::where('type', '=', Item::TYPE_POST)
                ->with('source.name')
                ->get()
                ->mapWithKeys(function ($item)
                return [$item->service->name => $item];
                )
                ->map(function ($items, $name)
                return [
                $name => $items->count()
                ];
                );


                Using Query



                DB::table('items')
                ->selectRaw('sources.name as name, count(*.items) as count')
                ->join('sources', 'sources.id', 'items.source_id')
                ->where('type', '=', Item::TYPE_POST)
                ->groupBy('sources.id')
                ->get()
                ->pluck('count', 'name')






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Mar 25 at 22:52









                Matt CMatt C

                5213 silver badges4 bronze badges




                5213 silver badges4 bronze badges


















                    Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.







                    Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.



















                    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%2f55345927%2fgroup-and-count-on-related-model%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

                    How to preserve electronics (computers, tablets and phones) for hundreds of years Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) The network's official Twitter account is up and running again. What content…How might modern humans leave a message for 50,000 years?How would an aquatic race develop computers?How do we make computers care for human life?Keeping supplies for 1000 yearsWhat will cell phones become in 100 years?What body armor protects against a laser?Could a society attain 1800s technology if limited to using copper and bronze?Electricity power (magic) and electronicsScavenging metal resources in post-apocalypse after 100 yearsWhy would precursors create devices that can survive and still work after hundreds of years?

                    155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해

                    Convert JSON to MapSimplest way to convert a string representing JSON array into Java array List of key value pairsHow to take String JSON values into HashMapConvert a JSON String to a HashMapCreating BSON object from JSON stringJSONObject - How to get a value ?Better Map ConstructorReading JSON from Url javaUpdate columns if input values are not null otherwise ignore and keep the existing values of column in databaseHow to store object represented as Json string into Couchbase Lite?Go JSON into MapHow do I efficiently iterate over each entry in a Java Map?Sort a Map<Key, Value> by valuesHow to round a number to n decimal places in JavaCan comments be used in JSON?How do I read / convert an InputStream into a String in Java?How can I pretty-print JSON in a shell script?What is the correct JSON content type?How can I deserialize JSON to a simple Dictionary<string,string> in ASP.NET?Why does Google prepend while(1); to their JSON responses?Parse JSON in JavaScript?