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

                    SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

                    은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현