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 532<br />

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

2 ->orderBy('name', 'desc')<br />

3 ->get();<br />

inRandomOrder<br />

The inRandomOrder method may be used to sort the query results randomly. For example, you may<br />

use this method to fetch a random user:<br />

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

2 ->inRandomOrder()<br />

3 ->first();<br />

groupBy / having / havingRaw<br />

The groupBy and having methods may be used to group the query results. The having method’s<br />

signature is similar to that of the where method:<br />

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

2 ->groupBy('account_id')<br />

3 ->having('account_id', '>', 100)<br />

4 ->get();<br />

The havingRaw method may be used to set a raw string as the value of the having clause. For example,<br />

we can find all of the departments with sales greater than $2,500:<br />

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

2 ->select('department', DB::raw('SUM(price) as total_sales'))<br />

3 ->groupBy('department')<br />

4 ->havingRaw('SUM(price) > 2500')<br />

5 ->get();

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

Saved successfully!

Ooh no, something went wrong!