Laravel Eloquent: Deeper Relationships with One Query

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello guys today i want to talk about eloquent relationships and specifically about deeper relationships than one level so generally we are working with has many belongs to or many too many these are the most popular types of relationships but what if you have a relationship some deeper level for example countries the table of countries then each country has some cities so city belongs to a country and then in the city something else happens so level number three for example shops and every shop belongs to a city and you have some tasks to query the data with using first level second eleventh and third level and belongs to isn't enough well it is enough but the query gets more complex how to deal with those three levels or even more levels deep with eloquent functions like has many through relationship and a few packages let me show you an example number one is what if you want to query the country list with the amount of shops per country so remember there's country and then there's city and then there's shop so you cannot immediately query the relationship unless you specify so called has many through relationship so if we go to country database model generally what you have is has many for the cities but you can also define a relationship called shops with return this has many through and then related table is shop with another related model which is city related to the shop via city or through city and then you can query the shops and not only that you can query with count so for example we will have country get and inside of that we'll have country with shops for example like this one okay app models country added here country and shops and in the index blade i've made an old school table even without any html even with older deprecated border one so for each of the countries shops count like this and let's try it out let's launch that page and we have the results this is zoomed in version i've seated 50 random shops so this is how you can query shop's count with has many through relationship or you can do it even with count of shops then you download all the shops models you load only the number of the shops and you access that with shops count as a property and if we refresh that the result should be the same it's absolutely the same and let's take a look at the query database query what is inside what is launching under the hood and for that we will install a package called debug bar so composer require barry vdh laravel debug bar i'm typing that from memory and that's all we need to do to install it we don't need to enable anything we just refresh the page and we have queries and this is the query actually let's zoom out a bit so we can actually read that so select country and then there's a sub query for select count from shops joining cities and joining the countries and this is one pretty fast eloquent query the second example is the other way around so what if you want to query the list of the shops and list the country for every shop and generally first i will show you the wrong way so getting all the shops and then we have relationships and relationships are described in model so shop belongs to a city and then if you click the city city belongs to a country and then after that controller in the blade file of index we do for each of the shops we show the name and we show shop city then country then name it is working so the list is here the problem however with that list is the amount of queries launched to the database so every time it's launching the city it is launching a query to the database and also to the country acquired to the database if we see the debug bar select from city select from countries are happening all the time for the 50 shops and there are 100 queries in total to avoid that of course we can use eager loading so shop with and then get shop with city dot country and then if we refresh there are only three queries so we get the shops we select from cities with only cities that we need and select from countries with only the countries that we need that is great three queries but another problem here is that we load all the cities and the countries although we don't really need the cities actually and 62 models and we load all the cities although they are not present in the table and to try to solve that problem we will use a package from jonas stoudenmeyer and he released quite a few packages about relationships and we will try a few of them in this video and one of them is called belongs to through which is the opposite of has many through so has many through is inside of laravel by default and belongs to through isn't available so let's install that package and define that relationship and let's see the amount of queries that we have we install the package then we need to define that relationship so belongs to through we need to use that trade in our shop model so we use that trade here and then we can define public function country from the shop return this belongs to through so belongs to a country class through city class and now we can try to use the country without any city directly here and in the index blade we don't need the city either so let's try it out remember there were three queries and 62 models we refresh the result is the same and two queries and 59 models so as you can see city is not present here at all and the query is of course a bit more complex it's through key something like that but it helps with performance and now let's go even deeper like literally deeper with a package called has many deep from the same jonas out in meyer so imagine we have the fourth level in the database and this is employees employee belongs to a shop which in turn shop belongs to a city city belongs to a country and what if you want to query country with the amount of employees per country something like that so let's install that package again this is not available in laravel eloquent by default and has many deep allows you to do something like this so has many deep with array of models with chaining them and let's try it out we install the package so copy this one paste into the console okay and now in our main country model we should have country model use this trade has relationships and then we can define what is the syntax comments has minideep so public function employees with return this has many deep to employee class with the array of models along the way so user and post in this case so this is the first level this is the second level so we have city class as the next level and shop class as another level and there can be multiple unlimited levels here and we will take a look at the query a bit later so this is our relationship for country employees and let's try to do that in the controller so let's get back to the previous example of country with count shops now let's do with current employees and let's comment that out and pass the countries and i've changed the blade to country and employees count and let's try it out refresh the page any errors no errors i've seated 200 employees and that actually works and this is the query select countries and then there's sub select join shops join cities and does everything under the hood so in one query we select everything and we have only three models for the country so we don't load any cities or shops or even employees we just load the numbers if you need all the models of employees of course you can do that with employees count like this as we did with countries with shops so instead of with count you do just with employees and that would do the same result here but with more queries and with more models because now you would load all the employees but again without intermediate models there's no city model loaded there's no shop model loaded only the query of first level and the last level that you need with pretty good performance so that's it about deeper levels of eloquent to recap you can use has many through from laravel eloquent or a few packages by jonas stoudenmeier and he has even more packages so you can check out his github profile for more stuff and if you want to know more about eloquent relationships in general one of my courses on teachable is called laravel eloquent expert level it's kind of old so it was created from i remember in laravel 6 even but eloquent hasn't changed since then so if you want four hours about eloquent with topics like observers accessors mutators seeds method properties in eloquent api all of those relationships as well actually let's expand it so collections relationships yeah so has money through is mentioned here as one of the lesson so you can check out that course or check out all of my courses on laravel daily teachable.com i urge you to subscribe to the yearly membership which you will use to get access to all the 20 courses and everything for a year ahead which i will release the next course i'm planning is on flutter and laravel api so to create mobile apps it's probably gonna be released in september i'm not in a rush with that because of some downtime and holiday but i will keep pushing courses on this teachable platform and yearly membership will help you to get those and see you guys in other videos
Info
Channel: Laravel Daily
Views: 37,598
Rating: undefined out of 5
Keywords:
Id: 5s-_SnVl-1g
Channel Id: undefined
Length: 10min 37sec (637 seconds)
Published: Fri Jul 09 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.