06.10.2016 Views

laravel-5

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Database: Query Builder 524<br />

Joins<br />

Inner Join Statement<br />

The query builder may also be used to write join statements. To perform a basic SQL “inner join”,<br />

you may use the join method on a query builder instance. The first argument passed to the join<br />

method is the name of the table you need to join to, while the remaining arguments specify the<br />

column constraints for the join. Of course, as you can see, you can join to multiple tables in a single<br />

query:<br />

1 $users = DB::table('users')<br />

2 ->join('contacts', 'users.id', '=', 'contacts.user_id')<br />

3 ->join('orders', 'users.id', '=', 'orders.user_id')<br />

4 ->select('users.*', 'contacts.phone', 'orders.price')<br />

5 ->get();<br />

Left Join Statement<br />

If you would like to perform a “left join” instead of an “inner join”, use the leftJoin method. The<br />

leftJoin method has the same signature as the join method:<br />

1 $users = DB::table('users')<br />

2 ->leftJoin('posts', 'users.id', '=', 'posts.user_id')<br />

3 ->get();<br />

Cross Join Statement<br />

To perform a “cross join” use the crossJoin method with the name of the table you wish to cross<br />

join to. Cross joins generate a cartesian product between the first table and the joined table:<br />

1 $users = DB::table('sizes')<br />

2 ->crossJoin('colours')<br />

3 ->get();

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!