{"id":711,"date":"2016-06-26T08:23:07","date_gmt":"2016-06-26T15:23:07","guid":{"rendered":"http:\/\/www.keganv.com\/?p=711"},"modified":"2016-06-26T09:26:03","modified_gmt":"2016-06-26T16:26:03","slug":"doctrine-orm-query-offsets-limits-made-simple","status":"publish","type":"post","link":"https:\/\/www.keganv.com\/doctrine-orm-query-offsets-limits-made-simple\/","title":{"rendered":"Doctrine ORM Query Offsets and Limits Made Simple"},"content":{"rendered":"<p><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/www.keganv.com\/wp-content\/uploads\/doctrine-offsets-limits-800x330.jpg\" alt=\"Doctrine ORM Query Offsets &amp; Limits\" width=\"800\" height=\"330\" class=\"aligncenter size-medium wp-image-736\" srcset=\"https:\/\/www.keganv.com\/wp-content\/uploads\/doctrine-offsets-limits.jpg 800w, https:\/\/www.keganv.com\/wp-content\/uploads\/doctrine-offsets-limits-768x317.jpg 768w\" sizes=\"(max-width: 800px) 100vw, 800px\" \/>Recently, I&#8217;ve been building a mobile app using <a href=\"http:\/\/ionic.io\/\" target=\"_blank\">Ionic<\/a> with a lazy loading feature. Utilizing the infinite scroll directive, when the user swipes and hits the end of the list, in this case a list of accounts, the mobile app request hits an API route I built that returns a JSON response inside a CRM (customer relationship management) system I am also working on, loading more to the list. Basically, it&#8217;s pagination.<br \/>\n<!--more--><\/p>\n<p>The CRM I am working on is built on top of the Symfony framework. Now, I know you might be thinking, well there are already great bundles that provide for pagination like <a href=\"https:\/\/github.com\/KnpLabs\/KnpPaginatorBundle\" target=\"_blank\">KNP Paginator<\/a>. While that&#8217;s true, and I&#8217;ve used these bundles in other applications, for this use case, it would be overkill. I just needed something where I could set my request parameters, <code>limit<\/code> and <code>offset<\/code>, to a GET request that would then return my JSON response for that set of account entities.<\/p>\n<p>Obviously, one could write a simple DQL query for the offset and the limit. However, complex fetches with joins in Doctrine aren&#8217;t as reliable. Below is a quote from the <a href=\"http:\/\/doctrine-orm.readthedocs.io\/projects\/doctrine-orm\/en\/latest\/tutorials\/pagination.html\" target=\"_blank\">Doctrine documentation<\/a>.<\/p>\n<blockquote><p>Paginating Doctrine queries is not as simple as you might think in the beginning. If you have complex fetch-join scenarios with one-to-many or many-to-many associations using the \u201cdefault\u201d LIMIT functionality of database vendors is not sufficient to get the correct results.<\/p><\/blockquote>\n<p>Doctrine Paginator class to the rescue! If you are using Doctrine 2.2 or later in your project, you have access to this class. Since the query I am using contains numerous joins and associations, this class is necessary and provided an easy to use interface that gave me exactly what I needed.<\/p>\n<p>Below is the code that makes the query to the database, then sends it to a private function that formats the results before sending it back to the API controller route which gives the JSON response or an exception.<\/p>\n<pre>\r\n    \/**\r\n     * @param int $offset\r\n     * @param int $limit\r\n     * @return array\r\n     *\/\r\n    public function getAccounts($offset = 0, $limit = 50)\r\n    {\r\n        $qb = $this->em\r\n            ->getRepository('AccountBundle:Account')\r\n            ->createQueryBuilder('account')\r\n            ->select('account, contact, primaryPhone, primaryEmail, primaryAddress, picture')\r\n            ->leftJoin('account.contact', 'contact')\r\n            ->leftJoin('contact.phones', 'primaryPhone', 'primaryPhone.primary = true')\r\n            ->leftJoin('contact.emails', 'primaryEmail', 'primaryEmail.primary = true')\r\n            ->leftJoin('contact.addresses', 'primaryAddress', 'primaryAddress.primary = true')\r\n            ->leftJoin('contact.picture', 'picture')\r\n            ->orderBy('contact.lastName', 'ASC')\r\n        ;\r\n\r\n        $qb ->setFirstResult($offset)\r\n            ->setMaxResults($limit);\r\n\r\n        $paginator = new Paginator($query, $fetchJoinCollection = true);\r\n\r\n        return $this->formatResults($paginator);\r\n    }\r\n<\/pre>\n<p>Below is the Ionic\/Angular controller function that gets called on infinite scroll. There is a scope variable that keeps track of the offset number, <code>$scope.offset<\/code>. Every time the <code>loadMore<\/code> function is called the <code>$scope.offset<\/code> variable is incremented by 50, to get the next group from the database, then merges it with the accounts already loaded in memory. The <code>loadMore<\/code> function also calls a method passing the two arguments of <code>offset<\/code> and <code>limit<\/code> from the account service that sends the actual request to the CRM and returns a promise.<\/p>\n<pre>\r\n        \/\/ Infinite Scroll\r\n        $scope.loadMore = function() {\r\n            $scope.offset = $scope.offset + 50;\r\n            var request = AccountService.loadAllAccounts($scope.offset, 50);\r\n            request.query().$promise.then(function(data) {\r\n                var count = 0;\r\n                angular.forEach(data, function(value, key) {\r\n                    this.push(value);\r\n                    count++;\r\n                }, $scope.accounts);\r\n\r\n                \/\/ If less than 50 records were sent back, disable infinite scroll\r\n                if (count < 50) {\r\n                    $scope.noMoreItemsAvailable = true;\r\n                }\r\n                $scope.$broadcast('scroll.infiniteScrollComplete');\r\n            }).catch(function(err) {\r\n                console.error(err);\r\n            });\r\n        };\r\n<\/pre>\n<p>Finally, here is the service method that returns the accounts from the CRM.<\/p>\n<pre>\r\n        this.loadAllAccounts = function(offset, limit) {\r\n            return $resource(apiUrl + '\/api\/rest\/' + apiVersion + '\/accounts.json',\r\n                {\r\n                    offset:  offset,\r\n                    limit:   limit\r\n                },\r\n                {\r\n                    query: {\r\n                        method: \"GET\",\r\n                        isArray: true,\r\n                        headers: { 'X-WSSE': wsseHeader(Auth.getUsername(), Auth.getKey()) }\r\n                    }\r\n                }\r\n            );\r\n        };\r\n\r\n<\/pre>\n<p>I hope you found this short tutorial helpful! Let me know in your comments below!<\/p>\n","protected":false},"excerpt":{"rendered":"Recently, I&#8217;ve been building a mobile app using Ionic with a lazy loading feature. Utilizing the infinite scroll directive, when the user swipes and hits the end of the list, in this case a list of accounts, the mobile app request hits an API route I built that returns a JSON response inside a CRM &#8230; <br\/> <a class=\"view-article btn btn-primary flip pull-left\" href=\"https:\/\/www.keganv.com\/doctrine-orm-query-offsets-limits-made-simple\/\"><span>View Article<\/span><\/a>","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[10],"tags":[],"class_list":["post-711","post","type-post","status-publish","format-standard","hentry","category-coding-programming"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v20.1 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Doctrine ORM Query Offsets and Limits Made Simple | KeganV<\/title>\n<meta name=\"description\" content=\"Easily set the offset and limit to paginate complex join Doctrine queries to achieve consistent results. See how I did it using Ionic\/Angular, and Symfony.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.keganv.com\/doctrine-orm-query-offsets-limits-made-simple\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Doctrine ORM Query Offsets and Limits Made Simple | KeganV\" \/>\n<meta property=\"og:description\" content=\"Easily set the offset and limit to paginate complex join Doctrine queries to achieve consistent results. See how I did it using Ionic\/Angular, and Symfony.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.keganv.com\/doctrine-orm-query-offsets-limits-made-simple\/\" \/>\n<meta property=\"og:site_name\" content=\"KeganV\" \/>\n<meta property=\"article:published_time\" content=\"2016-06-26T15:23:07+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2016-06-26T16:26:03+00:00\" \/>\n<meta property=\"og:image\" content=\"http:\/\/www.keganv.com\/wp-content\/uploads\/doctrine-offsets-limits-800x330.jpg\" \/>\n<meta name=\"author\" content=\"Kegan V.\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Kegan V.\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"3 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/www.keganv.com\/doctrine-orm-query-offsets-limits-made-simple\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/www.keganv.com\/doctrine-orm-query-offsets-limits-made-simple\/\"},\"author\":{\"name\":\"Kegan V.\",\"@id\":\"https:\/\/www.keganv.com\/#\/schema\/person\/412e7755f594475dc403b6d774b80276\"},\"headline\":\"Doctrine ORM Query Offsets and Limits Made Simple\",\"datePublished\":\"2016-06-26T15:23:07+00:00\",\"dateModified\":\"2016-06-26T16:26:03+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/www.keganv.com\/doctrine-orm-query-offsets-limits-made-simple\/\"},\"wordCount\":435,\"commentCount\":1,\"publisher\":{\"@id\":\"https:\/\/www.keganv.com\/#\/schema\/person\/412e7755f594475dc403b6d774b80276\"},\"articleSection\":[\"Coding &amp; Programming\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/www.keganv.com\/doctrine-orm-query-offsets-limits-made-simple\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/www.keganv.com\/doctrine-orm-query-offsets-limits-made-simple\/\",\"url\":\"https:\/\/www.keganv.com\/doctrine-orm-query-offsets-limits-made-simple\/\",\"name\":\"Doctrine ORM Query Offsets and Limits Made Simple | KeganV\",\"isPartOf\":{\"@id\":\"https:\/\/www.keganv.com\/#website\"},\"datePublished\":\"2016-06-26T15:23:07+00:00\",\"dateModified\":\"2016-06-26T16:26:03+00:00\",\"description\":\"Easily set the offset and limit to paginate complex join Doctrine queries to achieve consistent results. See how I did it using Ionic\/Angular, and Symfony.\",\"breadcrumb\":{\"@id\":\"https:\/\/www.keganv.com\/doctrine-orm-query-offsets-limits-made-simple\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/www.keganv.com\/doctrine-orm-query-offsets-limits-made-simple\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/www.keganv.com\/doctrine-orm-query-offsets-limits-made-simple\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/www.keganv.com\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Doctrine ORM Query Offsets and Limits Made Simple\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/www.keganv.com\/#website\",\"url\":\"https:\/\/www.keganv.com\/\",\"name\":\"KeganV\",\"description\":\"\",\"publisher\":{\"@id\":\"https:\/\/www.keganv.com\/#\/schema\/person\/412e7755f594475dc403b6d774b80276\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/www.keganv.com\/?s={search_term_string}\"},\"query-input\":\"required name=search_term_string\"}],\"inLanguage\":\"en-US\"},{\"@type\":[\"Person\",\"Organization\"],\"@id\":\"https:\/\/www.keganv.com\/#\/schema\/person\/412e7755f594475dc403b6d774b80276\",\"name\":\"Kegan V.\",\"logo\":{\"@id\":\"https:\/\/www.keganv.com\/#\/schema\/person\/image\/\"},\"sameAs\":[\"http:\/\/www.keganv.com\"]}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Doctrine ORM Query Offsets and Limits Made Simple | KeganV","description":"Easily set the offset and limit to paginate complex join Doctrine queries to achieve consistent results. See how I did it using Ionic\/Angular, and Symfony.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.keganv.com\/doctrine-orm-query-offsets-limits-made-simple\/","og_locale":"en_US","og_type":"article","og_title":"Doctrine ORM Query Offsets and Limits Made Simple | KeganV","og_description":"Easily set the offset and limit to paginate complex join Doctrine queries to achieve consistent results. See how I did it using Ionic\/Angular, and Symfony.","og_url":"https:\/\/www.keganv.com\/doctrine-orm-query-offsets-limits-made-simple\/","og_site_name":"KeganV","article_published_time":"2016-06-26T15:23:07+00:00","article_modified_time":"2016-06-26T16:26:03+00:00","og_image":[{"url":"http:\/\/www.keganv.com\/wp-content\/uploads\/doctrine-offsets-limits-800x330.jpg"}],"author":"Kegan V.","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Kegan V.","Est. reading time":"3 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/www.keganv.com\/doctrine-orm-query-offsets-limits-made-simple\/#article","isPartOf":{"@id":"https:\/\/www.keganv.com\/doctrine-orm-query-offsets-limits-made-simple\/"},"author":{"name":"Kegan V.","@id":"https:\/\/www.keganv.com\/#\/schema\/person\/412e7755f594475dc403b6d774b80276"},"headline":"Doctrine ORM Query Offsets and Limits Made Simple","datePublished":"2016-06-26T15:23:07+00:00","dateModified":"2016-06-26T16:26:03+00:00","mainEntityOfPage":{"@id":"https:\/\/www.keganv.com\/doctrine-orm-query-offsets-limits-made-simple\/"},"wordCount":435,"commentCount":1,"publisher":{"@id":"https:\/\/www.keganv.com\/#\/schema\/person\/412e7755f594475dc403b6d774b80276"},"articleSection":["Coding &amp; Programming"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/www.keganv.com\/doctrine-orm-query-offsets-limits-made-simple\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/www.keganv.com\/doctrine-orm-query-offsets-limits-made-simple\/","url":"https:\/\/www.keganv.com\/doctrine-orm-query-offsets-limits-made-simple\/","name":"Doctrine ORM Query Offsets and Limits Made Simple | KeganV","isPartOf":{"@id":"https:\/\/www.keganv.com\/#website"},"datePublished":"2016-06-26T15:23:07+00:00","dateModified":"2016-06-26T16:26:03+00:00","description":"Easily set the offset and limit to paginate complex join Doctrine queries to achieve consistent results. See how I did it using Ionic\/Angular, and Symfony.","breadcrumb":{"@id":"https:\/\/www.keganv.com\/doctrine-orm-query-offsets-limits-made-simple\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.keganv.com\/doctrine-orm-query-offsets-limits-made-simple\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/www.keganv.com\/doctrine-orm-query-offsets-limits-made-simple\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.keganv.com\/"},{"@type":"ListItem","position":2,"name":"Doctrine ORM Query Offsets and Limits Made Simple"}]},{"@type":"WebSite","@id":"https:\/\/www.keganv.com\/#website","url":"https:\/\/www.keganv.com\/","name":"KeganV","description":"","publisher":{"@id":"https:\/\/www.keganv.com\/#\/schema\/person\/412e7755f594475dc403b6d774b80276"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.keganv.com\/?s={search_term_string}"},"query-input":"required name=search_term_string"}],"inLanguage":"en-US"},{"@type":["Person","Organization"],"@id":"https:\/\/www.keganv.com\/#\/schema\/person\/412e7755f594475dc403b6d774b80276","name":"Kegan V.","logo":{"@id":"https:\/\/www.keganv.com\/#\/schema\/person\/image\/"},"sameAs":["http:\/\/www.keganv.com"]}]}},"_links":{"self":[{"href":"https:\/\/www.keganv.com\/api\/wp\/v2\/posts\/711"}],"collection":[{"href":"https:\/\/www.keganv.com\/api\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.keganv.com\/api\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.keganv.com\/api\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.keganv.com\/api\/wp\/v2\/comments?post=711"}],"version-history":[{"count":19,"href":"https:\/\/www.keganv.com\/api\/wp\/v2\/posts\/711\/revisions"}],"predecessor-version":[{"id":742,"href":"https:\/\/www.keganv.com\/api\/wp\/v2\/posts\/711\/revisions\/742"}],"wp:attachment":[{"href":"https:\/\/www.keganv.com\/api\/wp\/v2\/media?parent=711"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.keganv.com\/api\/wp\/v2\/categories?post=711"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.keganv.com\/api\/wp\/v2\/tags?post=711"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}