So I have a table that is related to my user table; let's call this user_address.
I want to join the user_address table onto my User table like
INNER JOIN user_address ON user_address.userid = user.ID
But I was wondering how to do this using the Auth Class/User Model in Laravel? I could add a relationship to the User Model class for the user_address, but that feels like it's causing another query because the user_address is always needed.
Instead of running Auth::user()->user_address->street_name I'd prefer to just do Auth::user()->street_name... but I'm unsure where I can perform the join in the Auth/User model classes.
Anyone have any information on this type of situation?
Read through this: http://laravel.com/docs/eloquent
Especially the section on eager loading.
Hi thanks for the reply;
That's still using two queries when I'm pretty sure I can perform this just using one query with a simple join on my user table; but I don't know how to make the User model join automatically when it's instantiated.
Are you sure? I don't have eloquent setup myself but the whole point behind eager loading is to reduce the number of queries. The documentation sure seems to indicate that a join will be performed.
Not that it will make any difference anyways for your use case. Extra queries are seldom a problem. If your application reaches the "millions of requests per second" stage then maybe you can do some optimization.
You might consider checking the forum that overflows with questions. They have dozens of experienced Laravel developers. I like sitepoint but it's not so good with these sorts of questions.
I think in the documentation it says two queries would be performed.
I will take a look at the forums and see if I can get some answers there, Thanks!
Eager loading will run 2 SELECT queries but thats much more faster and less expensive than a join. So you have to weigh in performance over personal comfort. Speaking of personal comfort, you won't be able to do the join you want straight up. You will need to add a query scope in your User model to make the join and fetch results and you will need to extend the Auth class to create your own which uses that query scope to load up the data.
This topic is now closed. New replies are no longer allowed.