SQL Builder
Introductionβ
Bow provides an API for building queries. The table method allows you to build a sql query based on the table name and returns an instance of Bow\Database\QueryBuilder::class.
use Bow\Database\Database
$builder = Database::table('users');
// => Instance \Bow\Database\QueryBuilder::class
You can also use the table helper:
$builder = table('users');
On Bow's QueryBuilder instance, there are several methods that let you build a SQL query.
For example, the toSql method, which lets you display the built query.
$builder->toSql();
// select * from `users`
Retrieving informationβ
To retrieve information with the builder, you should use the get method, which returns a collection, first, which returns null or a stdclass object, and last, which behaves like first except that it returns the last element of the query execution result.
Example with getβ
$builder = Database::table('users');
$users = $builder->get();
foreach ($users as $user) {
echo $user->name;
}
Note that you can pass an array to
getthat is a list of the columns for the projection, like this:$builder->get(['name']).
Example with firstβ
$user = table('users')->first();
// Empty
is_null($user)
// Ok
echo $user->name;
Example with lastβ
$user = $builder->last();
Adding restrictionsβ
Simple restrictionβ
With the builder, you can add simple restrictions to the SQL query construction using the where method.
$users = table('users')->where('id', 1)->get();
$users = table('users')->where('id', '!=', 1)->get();
The OR clauseβ
You can chain restrictions by adding an or to your query. The orWhere method lets you do this:
$users = table('users')->where('id', 1)->orWhere('name', 'Papac')->get();
You can see the result of the query construction with the toSql method.
$sql = table('users')->where('id', 1)->orWhere('id', 1)->toSql();
// => select * from `users` where id = 1 or id = 3;
Additional clausesβ
whereNull / whereNotNullβ
The whereNull method checks that the value of the given column is NULL:
$users = table('users')->whereNull('name')->get();
The whereNotNull method checks that the value of the column is not NULL:
$users = table('users')->whereNotNull('age')->get();
whereIn / whereNotInβ
The whereIn method checks that the value of a given column is contained in the given array:
$users = table('users')->whereIn('age', [27, 30])->get();
The whereNotIn method checks that the value of the given column is not contained in the given array:
$users = table('users')->whereNotIn('age', [27, 30])->get();
whereBetween / whereNotBetweenβ
The whereBetween method checks that the value of a column is between two values:
$users = table('users')->whereBetween('votes', [1, 100])->get();
The whereNotBetween method checks that the value of a column lies outside two values:
$users = table('users')->whereNotBetween('votes', [1, 100])->get();
Ordering, Grouping, and limitingβ
orderByβ
The orderBy method lets you sort the query result based on a given column. The first argument to the orderBy method should be the column you want to sort by, while the second argument controls the sort direction and may be asc or desc:
$users = table('users')->orderBy('name', 'desc')->get();
groupBy and havingβ
The groupBy and having methods can be used to group the query results. The signature of the having method is similar to that of the where method:
$users = table('orders')
->groupBy('price')
->having('price', '>', 100)
->get();
jump and takeβ
To limit the number of results returned by the query, or to skip a given number of results in the query, you can use the jump (to skip) and take (to return a number) methods:
$users = DB::table('users')->jump(10)->take(5)->get();
Aggregatesβ
The query builder also provides a variety of aggregate methods such as count, max, min, avg, and sum. You can call any of these methods after building your query.
$users = table('users')->count();
$price = table('orders')->max('price');
$avg = table('orders')->avg('price');
Determining if records existβ
Instead of using the count method to determine whether there are any records matching your query's constraints, you can use the exists method:
$exists = table('users')->where('id', 1)->exists();
Specifying a select clauseβ
Of course, you may not always want to select all the columns of a database table. Using the select method, you can specify a custom select clause for the query:
$price = table('orders')->select('price')->get();
// Or select multiple columns
$price = table('orders')->select(['id', 'price'])->get();
Inserting informationβ
The query builder also provides an insert method for inserting records into the database table. The insert method accepts an array of column names and values:
table('users')->insert(
['email' => 'exemple@gmail.com', 'age' => 27]
);
You can even insert several records into the table with a single call to insert by passing an array of arrays. Each array represents a row to be inserted into the table:
Updatingβ
Of course, in addition to inserting records into the database, the query builder can also update existing records using the update method. The update method, like the insert method, accepts an array of column and value pairs containing the columns to be updated. You can constrain the update query using where clauses:
table('users')->where('id', 1)->update(
['email' => 'exemple@gmail.com', 'age' => 27]
);
Deleting a recordβ
The query builder can also be used to delete records from the table via the delete method. You can constrain delete statements by adding where clauses before calling the delete method:
table('users')->delete();
table('users')->where('age', '>', 27)->delete();
If you want to empty the entire table, which will delete all rows and reset the auto-increment ID to zero, you can use the truncate method:
table('pets')->truncate();
Is something missing?
If you run into problems with the documentation or have suggestions to improve the documentation or the project in general, please open an issue for us, or send a tweet mentioning the Twitter account @bowframework or directly on github.