0

I have a users table and follows table and two models for both. I have user left join to fetch the data from the table, but I am confused to use which model and join table (i.e).

$user = Follows::select( 'users.id', 'users.username', 'users.photo' )                              
            ->leftJoin('users', 'follows.fk_users_id', '=', 'users.id')     
            ->where('follows.follower_users_id' ,'=', $id)
            ->get();

or

$user = Users::select( 'users.id', 'users.username', 'users.photo' )                                
            ->leftJoin('follows', 'follows.fk_users_id', '=', 'users.id')       
            ->where('follows.follower_users_id' ,'=', $id)
            ->get();

I am coding this in Follows model But I only need data from users table where it meets the condition with follows table, need your help as I am new to laravel.

My question is whether to use Follows model and left join users table or use Users model and left join follows table

Ronser
  • 1,855
  • 6
  • 20
  • 38
  • 1
    `But I only need data from users table where it meets the condition with follows table`.... in that case, use `inner join`? – itachi Nov 15 '14 at 16:33

2 Answers2

1

You can't really tell until you actually analyze the resulting SQL that Laravel/PDO creates under your conditions, i.e. how many rows in each table, existing indexes, etc. Here's a tip, introduce an error into each of the selects and capture the exception message. It will contain the raw query which you can fix up and apply to an analyzer, see MySql query analyzer - free solutions.

Community
  • 1
  • 1
John
  • 701
  • 6
  • 10
  • 2
    Introducing an error into a query just to get it dumped by the exception is not such a good idea. It's better to listen to the query event and log it `Event::listen('illuminate.query', function ($query) { });` or to use `$query->toSql()` to dump it. – Bogdan Nov 15 '14 at 13:22
  • @Bogdan but I haven't done that and don't know how to in laravel any reference link pls – Ronser Nov 15 '14 at 13:49
  • @Ronser To listen to events in Laravel check the [Events Docs](http://laravel.com/docs/4.2/events). To get the raw SQL query as a string use `->toSql()` instead of `->get()`. For debugging purposes I really like the [Laravel Debug Bar](https://github.com/barryvdh/laravel-debugbar) which also lists all the SQL query being run by the app. – Bogdan Nov 15 '14 at 14:19
0

Both the SQL JOINS are same in terms of SQL but when we look at ORM level in Laravel things change.

If we are using the Follows model then you will only be able to call the relationships defined in Follows model. If you use the Users model then you will be able to use the relationships defined against Users model.

NOTE Use explain in SQL and you will find the query execution path are same.

Max Gaurav
  • 1,835
  • 2
  • 13
  • 26