設定Configuration
Laravelはデータベースとの接続、クエリーの実行をとても簡単にしてくれます。データベース設定ファイルはconfig/database.php
です。このファイルで使用するデータベース接続を全部定義すると同時に、デフォルトで使用する接続も指定してください。サポートしている全データベースシステムの例はファイルの中にあります。Laravel makes connecting with
databases and running queries extremely simple. The
database configuration file is
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.
現在LaravelがサポートしてるデータベースシステムはMySQL、Postgres、SQLite、SQL Serverです。Currently Laravel supports four database systems: MySQL, Postgres, SQLite, and SQL Server.
Read/Write接続Read / Write Connections
場合により、SELECT文には別のデータベース接続を利用したい場合もあると思います。INSERT、UPDATE、DELETE文では、また他の接続に切り替えたい場合です。Laravelではこれは簡単に実現できます。SQLをそのまま使う場合であろうと、クエリービルダーやEloquent ORMを利用する場合であろうと、適切な接続が利用されます。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.
Read/Write接続を理解してもらうため、以下の例をご覧ください。To see how read / write connections should be configured, let's look at this example:
'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' => '',
],
設定配列にread
とwrite
、2つのキーが追加されたことに注目して下さい。2つのキーともhost
というキーを一つ持っています。read
とwrite
接続時の残りのデータベースオプションは、メインのmysql
配列からマージされます。ですから、read
とwrite
の配列には、メインの配列の値をオーバーライドしたいものだけ指定してください。この場合、192.168.1.1
は"read"接続に利用され、一方192.168.1.2
が"write"接続に利用されます。メインのmysql
配列に含まれる、データベース接続情報、プレフィックス、キャラクターセットなどその他のオプションは、両方の接続で共有されます。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.
クエリーの実行Running Queries
データベース接続の設定を済ませれば、DB
ファサードを使用しクエリーを実行できます。Once you have configured your
database connection, you may run queries using the
DB
facade.
SELECTクエリーを実行するRunning A Select Query
$results = DB::select('select * from users where id = ?', [1]);
select
メソッドはいつも結果を配列でリターンします。The select
method
will always return an array
of
results.
INSERT文を実行するRunning An Insert Statement
DB::insert('insert into users (id, name) values (?, ?)', [1, 'Dayle']);
UPDATE文を実行するRunning An Update Statement
DB::update('update users set votes = 100 where name = ?', ['John']);
DELETE文を実行するRunning A Delete Statement
DB::delete('delete from users');
注目:
update
とdelete
文はその操作により影響を受けるレコード数をリターンします。Note: Theupdate
anddelete
statements return the number of rows affected by the operation.
通常のSQL文を実行するRunning A General Statement
DB::statement('drop table users');
クエリーイベントをリッスンするListening For Query Events
DB::listen
メソッドを使用し、クエリーイベントをリッスンすることが可能です。You may listen for query events
using the DB::listen
method:
DB::listen(function($sql, $bindings, $time)
{
//
});
データベーストランザクションDatabase Transactions
データベーストランザクションを使用して一連の操作を実行する場合は、transaction
メソッドを使ってください。To run a set of operations within
a database transaction, you may use the
transaction
method:
DB::transaction(function()
{
DB::table('users')->update(['votes' => 1]);
DB::table('posts')->delete();
});
注意:
transaction
のクロージャーの中で、どんな例外が投げられても、自動的にそのトランザクションはロールバックされます。Note: Any exception thrown within thetransaction
closure will cause the transaction to be rolled back automatically.
場合により、自分でトランザクションを始める必要があることもあるでしょう。Sometimes you may need to begin a transaction yourself:
DB::beginTransaction();
トランザクションをロールバックするには、rollback
メソッドを使用します。You can rollback a transaction
via the rollback
method:
DB::rollback();
最後に、トランザクションのコミットは、commit
メソッドです。Lastly, you can commit a
transaction via the commit
method:
DB::commit();
コネクションとの接続Accessing Connections
複数のコネクションを使用するときはDB::connection
メソッドが使用できます。When using multiple connections,
you may access them via the
DB::connection
method:
$users = DB::connection('foo')->select(...);
裏で動いているPDOインスタンスにアクセスすることもできます。You may also access the raw, underlying PDO instance:
$pdo = DB::connection()->getPdo();
場合により、指定したデータベースに再接続する必要があるでしょう。Sometimes you may need to reconnect to a given database:
DB::reconnect('foo');
裏で動作しているPDOインスタンスのmax_connections
制限を超えてしまい、指定したデータベースとの接続を切りたい場合は、disconnect
メソッドを使用して下さい。If you need to disconnect from
the given database due to exceeding the underlying
PDO instance's max_connections
limit,
use the disconnect
method:
DB::disconnect('foo');
クエリーのログQuery Logging
デフォルトでLaravelは現在のリクエストで実行された全クエリーのログをメモリー上に保存しています。しかし、大量の行を挿入するような状況では、アプリケーションがメモリを使いすぎるでしょう。ログを止めるには、disableQueryLog
メソッドを使用してください。By default, Laravel keeps a log
in memory of all queries that have been run for the
current request. However, in some cases, such as
when inserting a large number of rows, this can
cause the application to use excess memory. To
disable the log, you may use the
disableQueryLog
method:
DB::connection()->disableQueryLog();
実行済みのクエリーの配列を取得するために、getQueryLog
メソッドが使用できます。To get an array of the executed
queries, you may use the getQueryLog
method:
$queries = DB::getQueryLog();