06.10.2016 Views

laravel-5

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Database: Query Builder 530<br />

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

2 ->whereYear('created_at', '2016');<br />

Advanced Where Clauses<br />

Parameter Grouping<br />

Sometimes you may need to create more advanced where clauses such as “where exists” or nested<br />

parameter groupings. The Laravel query builder can handle these as well. To get started, let’s look<br />

at an example of grouping constraints within parenthesis:<br />

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

2 ->where('name', '=', 'John')<br />

3 ->orWhere(function ($query) {<br />

4 $query->where('votes', '>', 100)<br />

5 ->where('title', '', 'Admin');<br />

6 })<br />

7 ->get();<br />

As you can see, passing a Closure into the orWhere method instructs the query builder to begin a<br />

constraint group. The Closure will receive a query builder instance which you can use to set the<br />

constraints that should be contained within the parenthesis group. The example above will produce<br />

the following SQL:<br />

1 select * from users where name = 'John' or (votes > 100 and title 'Admin')<br />

Exists Statements<br />

The whereExists method allows you to write where exists SQL clauses. The whereExists method<br />

accepts a Closure argument, which will receive a query builder instance allowing you to define the<br />

query that should be placed inside of the “exists” clause:

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

Saved successfully!

Ooh no, something went wrong!