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

                    Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                    Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

                    Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript