简介
Laravel makes connecting with databases and running queries extremely simple across a variety of database back-ends using either raw SQL, the fluent query builder, and the Eloquent ORM. Currently, Laravel supports four database systems:
Laravel让连接和使用数据库变得异常简单,对于不同数据库后台,使用原生SQL,或查询构建器,或Eloquent ORM都是如此,现在Laravel(5.1)支持四种数据系统
- MySQL
- Postgres
- SQLite
- SQL Server
#配置
Laravel makes connecting with databases and running queries extremely simple. The database configuration for your application is located at config/database.php
. In this file you may define all of your database connections, as well as specify which connection should be used by default. Examples for all of the supported database systems are provided in this file.
By default, Laravel's sample environment configuration is ready to use with Laravel Homestead, which is a convenient virtual machine for doing Laravel development on your local machine. Of course, you are free to modify this configuration as needed for your local database.
Laravel使连接数据库和运行查询异常简单,应用的数据库配置文件是 config/database.php, 在文件里,你可以定义各种数据库连接配置, 以及制定那个连接应该被默认使用,文件中被提供了所有被支持的数据库系统连接的配置。
默认,Laravel的范例环境配置已经准备好用于Laravel Homestead, 它是一个方便的虚拟机,可以用于在你本机上开发Laravel应用,当然你可以自由改变这个配置用于你自己的数据库
读写分离配置
Sometimes you may wish to use one database connection for SELECT statements, and another for INSERT, UPDATE, and DELETE statements. Laravel makes this a breeze, and the proper connections will always be used whether you are using raw queries, the query builder, or the Eloquent ORM.
To see how read / write connections should be configured, let's look at this example:
有时候,你可能希望使用特懂数据库连接用于查询操作,同事使用另外的连接用于INSERT, UPDATE,以及 DELETE 操作。 LARAVEL让这些变的轻松简单,并确保你不论在使用原始查找,查找构建器,或者是Eloquent ORM使用的都是正确的连接。
下面来看看如何配置读取/写入连接, 让我们来看看以下的例子
'mysql' => [
'read' => [
'host' => '192.168.1.1',
],
'write' => [
'host' => '196.168.1.2'
],
'driver' => 'mysql',
'database' => 'database',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
],
Note that two keys have been added to the configuration array: read
and write
. Both of these keys have array values containing a single key: host
. The rest of the database options for the read
and write
connections will be merged from the main mysql
array.
So, we only need to place items in the read
and write
arrays if we wish to override the values in the main array. So, in this case, 192.168.1.1
will be used as the "read" connection, while 192.168.1.2
will be used as the "write" connection. The database credentials, prefix, character set, and all other options in the main mysql
array will be shared across both connections.
注意我们加了两个键值到配置文件数组中: read
及 write
。 两个键值都包含了单一键值的数组:host
。read
及 write
的其余数据库配置会从mysql
数组中合并。 所以,如果我们想要覆写配置值,只要将选项放入 read
和 write
数组即可。 所以在上面的例子里, 192.168.1.1
将被用作「读取」连接,而 192.168.1.2
将被用作「写入」连接。数据库凭证、 前缀、字符编码配置、以及其他所有的配置会共用 mysql
数组里的配置。
运行原生SQL查询
Once you have configured your database connection, you may run queries using the DB
facade. The DB
facade provides methods for each type of query: select
, update
, insert
, and statement
.
一旦你配置好数据库连接你就可以通过DB facade执行查询, DB facade对不同数据操作提供了查询方法:select, update, insert, 和statement.
执行Select查找
To run a basic query, we can use the select
method on the DB
facade:
要运行一个基本查询,你可以使用DB facade 的 select方法
<?php
namespace AppHttpControllers;
use DB;
use AppHttpControllersController;
class UserController extends Controller
{
/**
* Show a list of all of the application's users.
*
* @return Response
*/
public function index()
{
$users = DB::select('select * from users where active = ?', [1]);
return view('user.index', ['users' => $users]);
}
}
The first argument passed to the select
method is the raw SQL query, while the second argument is any parameter bindings that need to be bound to the query. Typically, these are the values of the where
clause constraints. Parameter binding provides protection against SQL injection.
The select
method will always return an array
of results. Each result within the array will be a PHP StdClass
object, allowing you to access the values of the results:
第一个传入select方法的是一个原生SQL查询,第二个引数是需要绑定到查询语句的参数,通常,这些是where条件子句的值。 参数绑定防止了SQL注入的发生。
select方法会一直返回一个结果的数组,每个array中的结果都会是一个PHP StdClasss 对象, 允许你获得结果中的值。
foreach ($users as $user) {
echo $user->name;
}
使用名称绑定
Instead of using ?
to represent your parameter bindings, you may execute a query using named bindings:
相对于用?来表示参数绑定,你ikeyi运行一个使用命名绑定的查询
$results = DB::select('select * from users where id = :id', ['id' => 1]);
运行一个插入语法
To execute an insert
statement, you may use the insert
method on the DB
facade. Like select
, this method takes the raw SQL query as its first argument, and bindings as the second argument:
方法第一引数是查询语句,第二个引数是绑定
DB::insert('insert into users (id, name) values (?, ?)', [1, 'Dayle']);
运行一个更新语法
The update
method should be used to update existing records in the database. The number of rows affected by the statement will be returned by the method:
方法会返回被修改的行数
$affected = DB::update('update users set votes = 100 where name = ?', ['John']);
运行一个删除语法
The delete
method should be used to delete records from the database. Like update
, the number of rows deleted will be returned:
方法影响的行数被返回,就像更新操作一样。
$deleted = DB::delete('delete from users');
运行一个通用语句
Some database statements should not return any value. For these types of operations, you may use the statement
method on the DB
facade:
有些数据库操作不应该返回值,这些操作可以用statement方法来执行。
DB::statement('drop table users');
#监听查询事件
If you would like to receive each SQL query executed by your application, you may use the listen
method. This method is useful for logging queries or debugging. You may register your query listener in a service provider:
你将收到每个SQL查询执行产生的事件, 你可以使用 listen 方法,这个方法对于产生日志和调试很有用处, 你可以在服务提供者登记你的查询监听器。
<?php
namespace AppProviders;
use DB;
use IlluminateSupportServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
DB::listen(function($sql, $bindings, $time) {
//
});
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
//
}
}
数据库事务
To run a set of operations within a database transaction, you may use the transaction
method on the DB
facade. If an exception is thrown within the transaction Closure
, the transaction will automatically be rolled back. If the Closure
executes successfully, the transaction will automatically be committed. You don't need to worry about manually rolling back or committing while using the transaction
method:
要在数据库事务里运行一组操作, 你可以使用DB facade的 transaction方法,如果一个异常在事务的闭包函数中抛出, 整个事务都会回滚, 如果事务执行成功, 这个事务会自动提交, 你i无需担心手动回滚或提交。
DB::transaction(function () {
DB::table('users')->update(['votes' => 1]);
DB::table('posts')->delete();
});
手动使用事务
If you would like to begin a transaction manually and have complete control over rollbacks and commits, you may use the beginTransaction
method on the DB
facade:
你如果喜欢手动开始一个事务, 完全控制回滚和提交,你可以使用DB facade的 beginTransaction方法。
DB::beginTransaction();
You can rollback the transaction via the rollBack
method:
你可以回滚这个事务用rollBack方法:
DB::rollBack();
Lastly, you can commit a transaction via the commit
method:
最好你可以提交事务使用commit方法
DB::commit();
Note: 使用DB facade 的transaction方法也可以控制查询构建器和Eloquent ORM的事务.
Using Multiple Database Connections
When using multiple connections, you may access each connection via the connection
method on the DB
facade. The name
passed to the connection
method should correspond to one of the connections listed in yourconfig/database.php
configuration file:
当使用多个连接时, 你可以用DB facade的connection方法获取每个连接, 每个传送到connection方法的名字应该对应在config/database.php配置文件中列出的名字。
$users = DB::connection('foo')->select(...);
You may also access the raw, underlying PDO instance using the getPdo
method on a connection instance:
你在connection实例上使用getPdo方法可以获取原生,下面的PDO实例,
$pdo = DB::connection()->getPdo();