Symfony4.1 Doctrine ManyToMany Reduce No of Queries












1















I'm working on a project. Entity are Blog,Category,Tags. Blog and Tags are in ManyToMany Relation. My repository query to fetch data by Tags filter is.



CODE1:



/**
* @return BlogPost
*/
public function getAllActivePostsByTags($value, $order = "DESC", $currentPage = 1, $limit = 10)
{
$query = $this->createQueryBuilder('p')
// ->select('p','t')
->innerJoin('p.blogTags', 't')
->where('t.slug = :val')
->setParameter('val', $value)
->orderBy('p.id', $order)
->getQuery();

$paginator = $this->paginate($query, $currentPage, $limit);

return $paginator;
}


This code works fine. All the tags(No of tags in a post)are displayed correctly. But the No of DB Query is 14. Then When I uncomment select as this,



CODE2:



/**
* @return BlogPost
*/
public function getAllActivePostsByTags($value, $order = "DESC", $currentPage = 1, $limit = 10)
{
$query = $this->createQueryBuilder('p')
->select('p','t')
->innerJoin('p.blogTags', 't')
->where('t.slug = :val')
->setParameter('val', $value)
->orderBy('p.id', $order)
->getQuery();

$paginator = $this->paginate($query, $currentPage, $limit);

return $paginator;
}


No of Query is 9. But The Tags per Post is only one(Not displaying all the tags of a single post).



To be clear info:




  • It displays entire list of BlogPost.

  • But not all Tags of a Post.

  • Only one Tag per Post is shown.


Question: Is code1 is correct (No of DB Query = 14) or Do I have to tweak little bit to reduce no of DB Hits. Please guide me on this.










share|improve this question



























    1















    I'm working on a project. Entity are Blog,Category,Tags. Blog and Tags are in ManyToMany Relation. My repository query to fetch data by Tags filter is.



    CODE1:



    /**
    * @return BlogPost
    */
    public function getAllActivePostsByTags($value, $order = "DESC", $currentPage = 1, $limit = 10)
    {
    $query = $this->createQueryBuilder('p')
    // ->select('p','t')
    ->innerJoin('p.blogTags', 't')
    ->where('t.slug = :val')
    ->setParameter('val', $value)
    ->orderBy('p.id', $order)
    ->getQuery();

    $paginator = $this->paginate($query, $currentPage, $limit);

    return $paginator;
    }


    This code works fine. All the tags(No of tags in a post)are displayed correctly. But the No of DB Query is 14. Then When I uncomment select as this,



    CODE2:



    /**
    * @return BlogPost
    */
    public function getAllActivePostsByTags($value, $order = "DESC", $currentPage = 1, $limit = 10)
    {
    $query = $this->createQueryBuilder('p')
    ->select('p','t')
    ->innerJoin('p.blogTags', 't')
    ->where('t.slug = :val')
    ->setParameter('val', $value)
    ->orderBy('p.id', $order)
    ->getQuery();

    $paginator = $this->paginate($query, $currentPage, $limit);

    return $paginator;
    }


    No of Query is 9. But The Tags per Post is only one(Not displaying all the tags of a single post).



    To be clear info:




    • It displays entire list of BlogPost.

    • But not all Tags of a Post.

    • Only one Tag per Post is shown.


    Question: Is code1 is correct (No of DB Query = 14) or Do I have to tweak little bit to reduce no of DB Hits. Please guide me on this.










    share|improve this question

























      1












      1








      1


      1






      I'm working on a project. Entity are Blog,Category,Tags. Blog and Tags are in ManyToMany Relation. My repository query to fetch data by Tags filter is.



      CODE1:



      /**
      * @return BlogPost
      */
      public function getAllActivePostsByTags($value, $order = "DESC", $currentPage = 1, $limit = 10)
      {
      $query = $this->createQueryBuilder('p')
      // ->select('p','t')
      ->innerJoin('p.blogTags', 't')
      ->where('t.slug = :val')
      ->setParameter('val', $value)
      ->orderBy('p.id', $order)
      ->getQuery();

      $paginator = $this->paginate($query, $currentPage, $limit);

      return $paginator;
      }


      This code works fine. All the tags(No of tags in a post)are displayed correctly. But the No of DB Query is 14. Then When I uncomment select as this,



      CODE2:



      /**
      * @return BlogPost
      */
      public function getAllActivePostsByTags($value, $order = "DESC", $currentPage = 1, $limit = 10)
      {
      $query = $this->createQueryBuilder('p')
      ->select('p','t')
      ->innerJoin('p.blogTags', 't')
      ->where('t.slug = :val')
      ->setParameter('val', $value)
      ->orderBy('p.id', $order)
      ->getQuery();

      $paginator = $this->paginate($query, $currentPage, $limit);

      return $paginator;
      }


      No of Query is 9. But The Tags per Post is only one(Not displaying all the tags of a single post).



      To be clear info:




      • It displays entire list of BlogPost.

      • But not all Tags of a Post.

      • Only one Tag per Post is shown.


      Question: Is code1 is correct (No of DB Query = 14) or Do I have to tweak little bit to reduce no of DB Hits. Please guide me on this.










      share|improve this question














      I'm working on a project. Entity are Blog,Category,Tags. Blog and Tags are in ManyToMany Relation. My repository query to fetch data by Tags filter is.



      CODE1:



      /**
      * @return BlogPost
      */
      public function getAllActivePostsByTags($value, $order = "DESC", $currentPage = 1, $limit = 10)
      {
      $query = $this->createQueryBuilder('p')
      // ->select('p','t')
      ->innerJoin('p.blogTags', 't')
      ->where('t.slug = :val')
      ->setParameter('val', $value)
      ->orderBy('p.id', $order)
      ->getQuery();

      $paginator = $this->paginate($query, $currentPage, $limit);

      return $paginator;
      }


      This code works fine. All the tags(No of tags in a post)are displayed correctly. But the No of DB Query is 14. Then When I uncomment select as this,



      CODE2:



      /**
      * @return BlogPost
      */
      public function getAllActivePostsByTags($value, $order = "DESC", $currentPage = 1, $limit = 10)
      {
      $query = $this->createQueryBuilder('p')
      ->select('p','t')
      ->innerJoin('p.blogTags', 't')
      ->where('t.slug = :val')
      ->setParameter('val', $value)
      ->orderBy('p.id', $order)
      ->getQuery();

      $paginator = $this->paginate($query, $currentPage, $limit);

      return $paginator;
      }


      No of Query is 9. But The Tags per Post is only one(Not displaying all the tags of a single post).



      To be clear info:




      • It displays entire list of BlogPost.

      • But not all Tags of a Post.

      • Only one Tag per Post is shown.


      Question: Is code1 is correct (No of DB Query = 14) or Do I have to tweak little bit to reduce no of DB Hits. Please guide me on this.







      mysql orm doctrine many-to-many symfony4






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 20 '18 at 6:16









      Sudhakar KrishnanSudhakar Krishnan

      5361420




      5361420
























          2 Answers
          2






          active

          oldest

          votes


















          1














          This is the expected behaviour in both cases.



          Case 1) You just select the BlogPost entities. So you tell doctrine to fetch all BlogPosts that have the BlogTag that has slug = value.
          The SQL query produced returns only column values from the blog_post table and so only hydrates the BlogPost entities returned, it does not hydrate the collection of BlogTags inside each BlogPost.



          When you try to access the tags of a BlogPost a new query is generated to get and hydrate its collection.



          That is the reason you get more queries in this case.



          Case 2) You select also the filtered BlogTag entities, and doctrine hydrates(puts) only this filtered BlogTag to each BlogPost `s collection.



          When you try to access the BlogTags of a BlogPost, you get the filtered one that meets the condition in the querybuilder.



          To force doctrine to "reload" the data from the database, you should refresh the blogPost entity:



           $em->refresh($blogPost);


          and also include refrech option on cascade operations of the relation definition:



          @OneToMany(targetEntity="BlogTag", mappedBy="post", cascade={"refresh"})


          References:




          • what cascade refresh means in doctrine 2

          • refresh objects: different question but same solution






          share|improve this answer

































            0














            Thanks @Jannes Botis for refresh. But in my case the code itself is wrong. There need a slight change in it.



            BlogTags.php



            /**
            * @ORMManyToMany(targetEntity="BlogPost", mappedBy="blogTags")
            */
            private $blogPosts;


            BlogPost.php



            /**
            * @var Collection|BlogTags
            *
            * @ORMManyToMany(targetEntity="BlogTags", inversedBy="blogPosts", cascade={"refresh"})
            * @ORMJoinTable(
            * name="fz__blog_n_tag",
            * joinColumns={
            * @ORMJoinColumn(name="blog_id", referencedColumnName="id")
            * },
            * inverseJoinColumns={
            * @ORMJoinColumn(name="tag_id", referencedColumnName="id")
            * }
            * )
            * @ORMOrderBy({"name": "ASC"})
            */
            private $blogTags;


            This created the join_table. Allready I have a join_table. Although This code is for reference to someone.



            Controller.php



            // This is my old Code
            $bp = $em->getRepository('App:BlogPost')->getAllActivePostsByTags($slug, "DESC", $page, self::PAGE_LIMIT);
            // This is my New Code
            $bp = $em->getRepository('App:BlogTags')->getAllActivePostsByTags($slug, "DESC", $page, self::PAGE_LIMIT);


            Repository.php



            public function getAllActivePostsByTags($value, $order = "DESC", $currentPage = 1, $limit = 10)
            {
            $query = $this->createQueryBuilder('t')
            ->select('t','p','tx')
            ->innerJoin('t.blogPosts', 'p')
            ->innerJoin('p.blogTags', 'tx')
            ->where('p.isActive = :val1')
            ->andWhere('t.slug = :val2')
            ->setParameter('val1', true)
            ->setParameter('val2', $value)
            ->orderBy('p.id', $order)
            ->getQuery();

            $paginator = $this->paginate($query, $currentPage, $limit);

            return $paginator;
            }


            I not changed my old twig file completely. As it throws error at many places. Because now i'm using tags repo instead of blog. So i modified the twig with



            {% include 'frontend/page/blog_home.html.twig' with { 'bp':bp|first.blogPosts } %}


            Help me on this (twig file): There is only one tag, that's why |first twig filter
            Clarify me with this twig filter. Do I'm doing right. Give me suggestion to improve on it. I tried bp[0] This trows error.



            Finally: By using old code in controller it returns 14 db hits. Now it returns only 8. Even there are more tags in a post (but old one returns more).






            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%2f53387269%2fsymfony4-1-doctrine-manytomany-reduce-no-of-queries%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









              1














              This is the expected behaviour in both cases.



              Case 1) You just select the BlogPost entities. So you tell doctrine to fetch all BlogPosts that have the BlogTag that has slug = value.
              The SQL query produced returns only column values from the blog_post table and so only hydrates the BlogPost entities returned, it does not hydrate the collection of BlogTags inside each BlogPost.



              When you try to access the tags of a BlogPost a new query is generated to get and hydrate its collection.



              That is the reason you get more queries in this case.



              Case 2) You select also the filtered BlogTag entities, and doctrine hydrates(puts) only this filtered BlogTag to each BlogPost `s collection.



              When you try to access the BlogTags of a BlogPost, you get the filtered one that meets the condition in the querybuilder.



              To force doctrine to "reload" the data from the database, you should refresh the blogPost entity:



               $em->refresh($blogPost);


              and also include refrech option on cascade operations of the relation definition:



              @OneToMany(targetEntity="BlogTag", mappedBy="post", cascade={"refresh"})


              References:




              • what cascade refresh means in doctrine 2

              • refresh objects: different question but same solution






              share|improve this answer






























                1














                This is the expected behaviour in both cases.



                Case 1) You just select the BlogPost entities. So you tell doctrine to fetch all BlogPosts that have the BlogTag that has slug = value.
                The SQL query produced returns only column values from the blog_post table and so only hydrates the BlogPost entities returned, it does not hydrate the collection of BlogTags inside each BlogPost.



                When you try to access the tags of a BlogPost a new query is generated to get and hydrate its collection.



                That is the reason you get more queries in this case.



                Case 2) You select also the filtered BlogTag entities, and doctrine hydrates(puts) only this filtered BlogTag to each BlogPost `s collection.



                When you try to access the BlogTags of a BlogPost, you get the filtered one that meets the condition in the querybuilder.



                To force doctrine to "reload" the data from the database, you should refresh the blogPost entity:



                 $em->refresh($blogPost);


                and also include refrech option on cascade operations of the relation definition:



                @OneToMany(targetEntity="BlogTag", mappedBy="post", cascade={"refresh"})


                References:




                • what cascade refresh means in doctrine 2

                • refresh objects: different question but same solution






                share|improve this answer




























                  1












                  1








                  1







                  This is the expected behaviour in both cases.



                  Case 1) You just select the BlogPost entities. So you tell doctrine to fetch all BlogPosts that have the BlogTag that has slug = value.
                  The SQL query produced returns only column values from the blog_post table and so only hydrates the BlogPost entities returned, it does not hydrate the collection of BlogTags inside each BlogPost.



                  When you try to access the tags of a BlogPost a new query is generated to get and hydrate its collection.



                  That is the reason you get more queries in this case.



                  Case 2) You select also the filtered BlogTag entities, and doctrine hydrates(puts) only this filtered BlogTag to each BlogPost `s collection.



                  When you try to access the BlogTags of a BlogPost, you get the filtered one that meets the condition in the querybuilder.



                  To force doctrine to "reload" the data from the database, you should refresh the blogPost entity:



                   $em->refresh($blogPost);


                  and also include refrech option on cascade operations of the relation definition:



                  @OneToMany(targetEntity="BlogTag", mappedBy="post", cascade={"refresh"})


                  References:




                  • what cascade refresh means in doctrine 2

                  • refresh objects: different question but same solution






                  share|improve this answer















                  This is the expected behaviour in both cases.



                  Case 1) You just select the BlogPost entities. So you tell doctrine to fetch all BlogPosts that have the BlogTag that has slug = value.
                  The SQL query produced returns only column values from the blog_post table and so only hydrates the BlogPost entities returned, it does not hydrate the collection of BlogTags inside each BlogPost.



                  When you try to access the tags of a BlogPost a new query is generated to get and hydrate its collection.



                  That is the reason you get more queries in this case.



                  Case 2) You select also the filtered BlogTag entities, and doctrine hydrates(puts) only this filtered BlogTag to each BlogPost `s collection.



                  When you try to access the BlogTags of a BlogPost, you get the filtered one that meets the condition in the querybuilder.



                  To force doctrine to "reload" the data from the database, you should refresh the blogPost entity:



                   $em->refresh($blogPost);


                  and also include refrech option on cascade operations of the relation definition:



                  @OneToMany(targetEntity="BlogTag", mappedBy="post", cascade={"refresh"})


                  References:




                  • what cascade refresh means in doctrine 2

                  • refresh objects: different question but same solution







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Dec 27 '18 at 23:21

























                  answered Dec 16 '18 at 14:03









                  Jannes BotisJannes Botis

                  6,65421125




                  6,65421125

























                      0














                      Thanks @Jannes Botis for refresh. But in my case the code itself is wrong. There need a slight change in it.



                      BlogTags.php



                      /**
                      * @ORMManyToMany(targetEntity="BlogPost", mappedBy="blogTags")
                      */
                      private $blogPosts;


                      BlogPost.php



                      /**
                      * @var Collection|BlogTags
                      *
                      * @ORMManyToMany(targetEntity="BlogTags", inversedBy="blogPosts", cascade={"refresh"})
                      * @ORMJoinTable(
                      * name="fz__blog_n_tag",
                      * joinColumns={
                      * @ORMJoinColumn(name="blog_id", referencedColumnName="id")
                      * },
                      * inverseJoinColumns={
                      * @ORMJoinColumn(name="tag_id", referencedColumnName="id")
                      * }
                      * )
                      * @ORMOrderBy({"name": "ASC"})
                      */
                      private $blogTags;


                      This created the join_table. Allready I have a join_table. Although This code is for reference to someone.



                      Controller.php



                      // This is my old Code
                      $bp = $em->getRepository('App:BlogPost')->getAllActivePostsByTags($slug, "DESC", $page, self::PAGE_LIMIT);
                      // This is my New Code
                      $bp = $em->getRepository('App:BlogTags')->getAllActivePostsByTags($slug, "DESC", $page, self::PAGE_LIMIT);


                      Repository.php



                      public function getAllActivePostsByTags($value, $order = "DESC", $currentPage = 1, $limit = 10)
                      {
                      $query = $this->createQueryBuilder('t')
                      ->select('t','p','tx')
                      ->innerJoin('t.blogPosts', 'p')
                      ->innerJoin('p.blogTags', 'tx')
                      ->where('p.isActive = :val1')
                      ->andWhere('t.slug = :val2')
                      ->setParameter('val1', true)
                      ->setParameter('val2', $value)
                      ->orderBy('p.id', $order)
                      ->getQuery();

                      $paginator = $this->paginate($query, $currentPage, $limit);

                      return $paginator;
                      }


                      I not changed my old twig file completely. As it throws error at many places. Because now i'm using tags repo instead of blog. So i modified the twig with



                      {% include 'frontend/page/blog_home.html.twig' with { 'bp':bp|first.blogPosts } %}


                      Help me on this (twig file): There is only one tag, that's why |first twig filter
                      Clarify me with this twig filter. Do I'm doing right. Give me suggestion to improve on it. I tried bp[0] This trows error.



                      Finally: By using old code in controller it returns 14 db hits. Now it returns only 8. Even there are more tags in a post (but old one returns more).






                      share|improve this answer




























                        0














                        Thanks @Jannes Botis for refresh. But in my case the code itself is wrong. There need a slight change in it.



                        BlogTags.php



                        /**
                        * @ORMManyToMany(targetEntity="BlogPost", mappedBy="blogTags")
                        */
                        private $blogPosts;


                        BlogPost.php



                        /**
                        * @var Collection|BlogTags
                        *
                        * @ORMManyToMany(targetEntity="BlogTags", inversedBy="blogPosts", cascade={"refresh"})
                        * @ORMJoinTable(
                        * name="fz__blog_n_tag",
                        * joinColumns={
                        * @ORMJoinColumn(name="blog_id", referencedColumnName="id")
                        * },
                        * inverseJoinColumns={
                        * @ORMJoinColumn(name="tag_id", referencedColumnName="id")
                        * }
                        * )
                        * @ORMOrderBy({"name": "ASC"})
                        */
                        private $blogTags;


                        This created the join_table. Allready I have a join_table. Although This code is for reference to someone.



                        Controller.php



                        // This is my old Code
                        $bp = $em->getRepository('App:BlogPost')->getAllActivePostsByTags($slug, "DESC", $page, self::PAGE_LIMIT);
                        // This is my New Code
                        $bp = $em->getRepository('App:BlogTags')->getAllActivePostsByTags($slug, "DESC", $page, self::PAGE_LIMIT);


                        Repository.php



                        public function getAllActivePostsByTags($value, $order = "DESC", $currentPage = 1, $limit = 10)
                        {
                        $query = $this->createQueryBuilder('t')
                        ->select('t','p','tx')
                        ->innerJoin('t.blogPosts', 'p')
                        ->innerJoin('p.blogTags', 'tx')
                        ->where('p.isActive = :val1')
                        ->andWhere('t.slug = :val2')
                        ->setParameter('val1', true)
                        ->setParameter('val2', $value)
                        ->orderBy('p.id', $order)
                        ->getQuery();

                        $paginator = $this->paginate($query, $currentPage, $limit);

                        return $paginator;
                        }


                        I not changed my old twig file completely. As it throws error at many places. Because now i'm using tags repo instead of blog. So i modified the twig with



                        {% include 'frontend/page/blog_home.html.twig' with { 'bp':bp|first.blogPosts } %}


                        Help me on this (twig file): There is only one tag, that's why |first twig filter
                        Clarify me with this twig filter. Do I'm doing right. Give me suggestion to improve on it. I tried bp[0] This trows error.



                        Finally: By using old code in controller it returns 14 db hits. Now it returns only 8. Even there are more tags in a post (but old one returns more).






                        share|improve this answer


























                          0












                          0








                          0







                          Thanks @Jannes Botis for refresh. But in my case the code itself is wrong. There need a slight change in it.



                          BlogTags.php



                          /**
                          * @ORMManyToMany(targetEntity="BlogPost", mappedBy="blogTags")
                          */
                          private $blogPosts;


                          BlogPost.php



                          /**
                          * @var Collection|BlogTags
                          *
                          * @ORMManyToMany(targetEntity="BlogTags", inversedBy="blogPosts", cascade={"refresh"})
                          * @ORMJoinTable(
                          * name="fz__blog_n_tag",
                          * joinColumns={
                          * @ORMJoinColumn(name="blog_id", referencedColumnName="id")
                          * },
                          * inverseJoinColumns={
                          * @ORMJoinColumn(name="tag_id", referencedColumnName="id")
                          * }
                          * )
                          * @ORMOrderBy({"name": "ASC"})
                          */
                          private $blogTags;


                          This created the join_table. Allready I have a join_table. Although This code is for reference to someone.



                          Controller.php



                          // This is my old Code
                          $bp = $em->getRepository('App:BlogPost')->getAllActivePostsByTags($slug, "DESC", $page, self::PAGE_LIMIT);
                          // This is my New Code
                          $bp = $em->getRepository('App:BlogTags')->getAllActivePostsByTags($slug, "DESC", $page, self::PAGE_LIMIT);


                          Repository.php



                          public function getAllActivePostsByTags($value, $order = "DESC", $currentPage = 1, $limit = 10)
                          {
                          $query = $this->createQueryBuilder('t')
                          ->select('t','p','tx')
                          ->innerJoin('t.blogPosts', 'p')
                          ->innerJoin('p.blogTags', 'tx')
                          ->where('p.isActive = :val1')
                          ->andWhere('t.slug = :val2')
                          ->setParameter('val1', true)
                          ->setParameter('val2', $value)
                          ->orderBy('p.id', $order)
                          ->getQuery();

                          $paginator = $this->paginate($query, $currentPage, $limit);

                          return $paginator;
                          }


                          I not changed my old twig file completely. As it throws error at many places. Because now i'm using tags repo instead of blog. So i modified the twig with



                          {% include 'frontend/page/blog_home.html.twig' with { 'bp':bp|first.blogPosts } %}


                          Help me on this (twig file): There is only one tag, that's why |first twig filter
                          Clarify me with this twig filter. Do I'm doing right. Give me suggestion to improve on it. I tried bp[0] This trows error.



                          Finally: By using old code in controller it returns 14 db hits. Now it returns only 8. Even there are more tags in a post (but old one returns more).






                          share|improve this answer













                          Thanks @Jannes Botis for refresh. But in my case the code itself is wrong. There need a slight change in it.



                          BlogTags.php



                          /**
                          * @ORMManyToMany(targetEntity="BlogPost", mappedBy="blogTags")
                          */
                          private $blogPosts;


                          BlogPost.php



                          /**
                          * @var Collection|BlogTags
                          *
                          * @ORMManyToMany(targetEntity="BlogTags", inversedBy="blogPosts", cascade={"refresh"})
                          * @ORMJoinTable(
                          * name="fz__blog_n_tag",
                          * joinColumns={
                          * @ORMJoinColumn(name="blog_id", referencedColumnName="id")
                          * },
                          * inverseJoinColumns={
                          * @ORMJoinColumn(name="tag_id", referencedColumnName="id")
                          * }
                          * )
                          * @ORMOrderBy({"name": "ASC"})
                          */
                          private $blogTags;


                          This created the join_table. Allready I have a join_table. Although This code is for reference to someone.



                          Controller.php



                          // This is my old Code
                          $bp = $em->getRepository('App:BlogPost')->getAllActivePostsByTags($slug, "DESC", $page, self::PAGE_LIMIT);
                          // This is my New Code
                          $bp = $em->getRepository('App:BlogTags')->getAllActivePostsByTags($slug, "DESC", $page, self::PAGE_LIMIT);


                          Repository.php



                          public function getAllActivePostsByTags($value, $order = "DESC", $currentPage = 1, $limit = 10)
                          {
                          $query = $this->createQueryBuilder('t')
                          ->select('t','p','tx')
                          ->innerJoin('t.blogPosts', 'p')
                          ->innerJoin('p.blogTags', 'tx')
                          ->where('p.isActive = :val1')
                          ->andWhere('t.slug = :val2')
                          ->setParameter('val1', true)
                          ->setParameter('val2', $value)
                          ->orderBy('p.id', $order)
                          ->getQuery();

                          $paginator = $this->paginate($query, $currentPage, $limit);

                          return $paginator;
                          }


                          I not changed my old twig file completely. As it throws error at many places. Because now i'm using tags repo instead of blog. So i modified the twig with



                          {% include 'frontend/page/blog_home.html.twig' with { 'bp':bp|first.blogPosts } %}


                          Help me on this (twig file): There is only one tag, that's why |first twig filter
                          Clarify me with this twig filter. Do I'm doing right. Give me suggestion to improve on it. I tried bp[0] This trows error.



                          Finally: By using old code in controller it returns 14 db hits. Now it returns only 8. Even there are more tags in a post (but old one returns more).







                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Jan 27 at 9:49









                          Sudhakar KrishnanSudhakar Krishnan

                          5361420




                          5361420






























                              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%2f53387269%2fsymfony4-1-doctrine-manytomany-reduce-no-of-queries%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