Laravel's wide wide world of (personal) choice

Database Eloquent Relationships

Committed to the LaraBrain by: harrisoftware at October 22, 2015 3:07 am

How to query a database

I came across this post recently while searching for the answer to one problem or another and I thought that it was an excellent review of Laravel's flexibility.

Different ways of querying:

Given these tables: Users [id, name] Posts [id, content, user_id], select all post from specific user:

/* First Way */ 
$user=User::find(1); // Just Eloquent 
$posts=$user->posts; // Just Eloquent

/* Second Way */ 
$posts=User::with('posts')->find(1); // Eloquent with Eager loading

/* Third Way */ 
$posts=User::find(1)->load('posts'); // Eloquent with Lazy Eager Loading 

/* Fourth Way */ 
$posts=User::join('posts','','=','posts.user_id')->where('',1)->get(); // Eloquent with Query Builder methods 

/* Fifth Way */
$posts=DB::table('users')->join('posts','','=','posts.user_id')->where('',1)->get(); // Just Query Builder 

/* Sixth Way */ 
$posts=DB::select('select * from users join posts on = posts.user_id where = 1'); // Just SQL

// no need for eager loading, as we're grabbing only one record from Users table
$posts = User::find(1)->posts()->get();

// even better - if we don't need user's data, we can avoid that select.

$posts =     User::posts()->where('user_id',1)->get();

// eager load with condition

$user_id = 1;
$posts = Posts::whereHas( function($query) use ($user_id) {

// if we still need user's data, but posts are our main output - consider creating hasOne reverse relationship in post

$posts = Posts::with('user')->all();