イントロダクションIntroduction
LaravelはSQLを直接使用する場合でも、FluentクエリビルダやEloquent ORMを使う時でも、データベースの取り扱いをとても簡単にしてくれます。現在、Laravelは以下のデータベースシステムを使用しています。Laravel makes interacting with databases extremely simple across a variety of database backends using either raw SQL, the fluent query builder[/docs/{{version}}/queries], and the Eloquent ORM[/docs/{{version}}/eloquent]. Currently, Laravel supports four databases:
設定Configuration
データベース設定ファイルはconfig/database.phpです。このファイルで使用するデータベース接続を全部定義すると同時に、デフォルトで使用する接続も指定してください。サポートしているほとんどのデータベースシステムの例がファイルの中に用意しています。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 most of the supported database systems are provided in this file.
デフォルトでLaravelのサンプル環境設定は、ローカルマシン上でLaravelでの開発を行うのに便利な仮想マシンであるLaravel Homestead用に設定してあります。もちろん、ローカルのデータベースに合わせるため、自由に変更してくだい。By default, Laravel's sample environment configuration[/docs/{{version}}/configuration#environment-configuration] is ready to use with Laravel Homestead[/docs/{{version}}/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.
SQLite設定SQLite Configuration
touch database/database.sqliteなどのコマンドを使い、新しいSQLiteデータベースを作成した後、この新しいデータベースの絶対パスを環境変数へ設定します。After creating a new SQLite database using a command such as touch database/database.sqlite, you can easily configure your environment variables to point to this newly created database by using the database's absolute path:
DB_CONNECTION=sqlite
DB_DATABASE=/absolute/path/to/database.sqlite
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'],
],
'sticky' => true,
'driver' => 'mysql',
'database' => 'database',
'username' => 'root',
'password' => '',
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
],
設定配列にreadとwrite、sticky、3つのキーが追加されたことに注目して下さい。2つのキーともhostというキーを一つ持っています。readとwrite接続時の残りのデータベースオプションは、メインのmysql配列からマージされます。Note that three keys have been added to the configuration array: read, write and sticky. The read and write 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.
readとwriteの配列には、メインの配列の値をオーバーライドしたいものだけ指定してください。この場合、192.168.1.1は"read"接続に利用され、一方192.168.1.2が"write"接続に利用されます。メインのmysql配列に含まれる、データベース接続情報、プレフィックス、文字セットなどその他のオプションは、両方の接続で共有されます。You only need to place items in the read and write arrays if you wish to override the values from the main array. So, in this case, 192.168.1.1 will be used as the host for the "read" connection, while 192.168.1.2 will be used for the "write" connection. The database credentials, prefix, character set, and all other options in the main mysql array will be shared across both connections.
stickyオプションThe sticky Option
stickyオプションはオプショナル値で、現在のリクエストサイクル中にデータベースへ書き込まれたレコードを即時に読み込めるようにします。stickyオプションが有効で、現在のリクエストサイクル中にデータベースに対して「書き込み(write)」処理が実行されると、すべての「読み込み(read)」操作で"write"接続が使われるようになります。これによりリクエストサイクル中に書き込まれたデータが、同じリクエスト中にデータベースから即時に読み込まれることが確実になります。The sticky option is an optional value that can be used to allow the immediate reading of records that have been written to the database during the current request cycle. If the sticky option is enabled and a "write" operation has been performed against the database during the current request cycle, any further "read" operations will use the "write" connection. This ensures that any data written during the request cycle can be immediately read back from the database during that same request. It is up to you to decide if this is the desired behavior for your application.
複数接続の使用Using Multiple Database Connections
複数の接続を使用する場合は、DBファサードのconnectionメソッドを利用し、各接続にアクセスできます。connectionメソッドに渡す「名前」は、config/database.php設定ファイルの中の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 your config/database.php configuration file:
$users = DB::connection('foo')->select(...);
裏で動作しているPDOインスタンスに直接アクセスしたい場合は、接続インスタンスにgetPdoメソッドを使います。You may also access the raw, underlying PDO instance using the getPdo method on a connection instance:
$pdo = DB::connection()->getPdo();
SQLクエリの実行Running Raw SQL Queries
データベース接続の設定を済ませれば、DBファサードを使用しクエリを実行できます。DBファサードは select、update、insert、delete、statementのクエリタイプごとにメソッドを用意しています。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, delete, and statement.
SELECTクエリの実行Running A Select Query
基本的なクエリを行うには、DBファサードのselectメソッドを使います。To run a basic query, you may use the select method on the DB facade:
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
class UserController extends Controller
{
/**
* アプリケーションの全ユーザーリストを表示
*
* @return Response
*/
public function index()
{
$users = DB::select('select * from users where active = ?', [1]);
return view('user.index', ['users' => $users]);
}
}
selectメソッドの最初の引数はSQLクエリで、2つ目の引数はクエリに結合する必要のあるパラメーターです。通常、パラメーターはwhere節制約の値です。パラメーター結合はSQLインジェクションを防ぐために提供されています。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.
selectメソッドはいつも結果の「配列」を返します。結果の値へアクセスできるように、配列に含まれる結果はそれぞれ、PHPのStdClassオブジェクトになります。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:
foreach ($users as $user) {
echo $user->name;
}
名前付き結合の使用Using Named Bindings
パラメーター結合に?を使う代わりに名前付きの結合でクエリを実行できます。Instead of using ? to represent your parameter bindings, you may execute a query using named bindings:
$results = DB::select('select * from users where id = :id', ['id' => 1]);
INSERT文の実行Running An Insert Statement
insert文を実行するには、DBファサードのinsertメソッドを使います。selectと同様に、このメソッドは第1引数にSQLクエリそのもの、第2引数に結合を取ります。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 its second argument:
DB::insert('insert into users (id, name) values (?, ?)', [1, 'Dayle']);
UPDATE文の実行Running An Update Statement
データベースの既存レコードの更新には、updateメソッドを使います。このメソッドの返却値は影響を受けたレコード数です。The update method should be used to update existing records in the database. The number of rows affected by the statement will be returned:
$affected = DB::update('update users set votes = 100 where name = ?', ['John']);
DELETE文の実行Running A Delete Statement
データベースからレコードを削除するには、deleteメソッドを使います。updateと同様に、削除したレコード数が返されます。The delete method should be used to delete records from the database. Like update, the number of rows affected will be returned:
$deleted = DB::delete('delete from users');
通常のSQL文を実行するRunning A General Statement
いつくかのデータベース文は値を返しません。こうしたタイプの操作には、DBファサードのstatementメソッドを使います。Some database statements do not return any value. For these types of operations, you may use the statement method on the DB facade:
DB::statement('drop table users');
クエリイベントのリッスンListening For Query Events
アプリケーションで実行される各SQLクエリを取得したい場合は、listenメソッドが使用できます。このメソッドはクエリをログしたり、デバッグしたりするときに便利です。クエリリスナはサービスプロバイダの中で登録します。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[/docs/{{version}}/providers]:
<?php
namespace App\Providers;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* アプリケーションサービスの初期処理
*
* @return void
*/
public function boot()
{
DB::listen(function ($query) {
// $query->sql
// $query->bindings
// $query->time
});
}
/**
* サービスプロバイダの登録
*
* @return void
*/
public function register()
{
//
}
}
データベーストランザクションDatabase Transactions
一連の操作をデータベーストランザクション内で実行するには、DBファサードのtransactionメソッドを使用してください。トランザクション「クロージャ」の中で例外が投げられると、トランザクションは自動的にロールバックされます。「クロージャ」が正しく実行されると、自動的にコミットされます。transactionメソッドを使用すれば、ロールバックやコミットを自分でコードする必要はありません。You may use the transaction method on the DB facade to run a set of operations within a database transaction. 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::transaction(function () {
DB::table('users')->update(['votes' => 1]);
DB::table('posts')->delete();
});
デッドロックの処理Handling Deadlocks
transactionメソッドは第2引数に、デッドロック発生時のトランザクション再試行回数を指定できます。試行回数を過ぎたら、例外が投げられます。The transaction method accepts an optional second argument which defines the number of times a transaction should be reattempted when a deadlock occurs. Once these attempts have been exhausted, an exception will be thrown:
DB::transaction(function () {
DB::table('users')->update(['votes' => 1]);
DB::table('posts')->delete();
}, 5);
手動トランザクションManually Using Transactions
トランザクションを自分で開始し、ロールバックとコミットを完全にコントロールしたい場合は、DBファサードのbeginTransactionメソッドを使います。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::beginTransaction();
rollBackメソッドにより、トランザクションをロールバックできます。You can rollback the transaction via the rollBack method:
DB::rollBack();
同様に、commitメソッドにより、トランザクションをコミットできます。Lastly, you can commit a transaction via the commit method:
DB::commit();
">Tip!!
DBファサードのトランザクションメソッドは、クエリビルダとEloquent ORMのトランザクションを両方共にコントロールします。{tip} TheDBfacade's transaction methods control the transactions for both the query builder[/docs/{{version}}/queries] and Eloquent ORM[/docs/{{version}}/eloquent].