イントロダクションIntroduction
LaravelはたとえSQLを直接使用する場合でも、FluentクエリービルダーやEloquent ORMを使う時でも、データベースとの接続、クエリーの実行をとても簡単にしてくれます。現在、Laravelは以下のデータベースシステムを使用しています。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[/docs/{{version}}/queries], and the Eloquent ORM[/docs/{{version}}/eloquent]. Currently, Laravel supports four database systems:
- MySQLMySQL
- PostgresPostgres
- SQLiteSQLite
- SQL ServerSQL Server
設定Configuration
Laravelはデータベースとの接続、クエリーの実行をとても簡単にしてくれます。データベース設定ファイルはconfig/database.php
です。このファイルで使用するデータベース接続を全部定義すると同時に、デフォルトで使用する接続も指定してください。サポートしている全データベースシステムの例がファイルの中に用意しています。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.
デフォルトでLaravelのサンプル環境設定は、ローカルマシーン上でLaravelでの開発を行うのに便利な仮想マシーンであるLaravel Homestead用に設定してあります。もちろん、ローカルのデータベースに合わせるため、自由に変更してくだい。By default, Laravel's sample environment configuration[/docs/{{version}}/installation#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.
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
配列からマージされます。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.
ですから、read
とwrite
の配列には、メインの配列の値をオーバーライドしたいものだけ指定してください。この場合、192.168.1.1
は"read"接続に利用され、一方192.168.1.2
が"write"接続に利用されます。メインのmysql
配列に含まれる、データベース接続情報、プレフィックス、文字セットなどその他のオプションは、両方の接続で共有されます。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.
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, we can use the
select
method on the
DB
facade:
<?php
namespace App\Http\Controllers;
use 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
メソッドを使います。このメソッドは第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 the 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 by the method:
$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 deleted will be
returned:
$deleted = DB::delete('delete from users');
通常のSQL文を実行するRunning A General Statement
いつくかのデータベース文は値を返しません。こうしたタイプの操作には、DB
ファサードのstatement
メソッドを使います。Some database
statements should 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 DB;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* アプリケーションサービスの初期処理
*
* @return void
*/
public function boot()
{
DB::listen(function($sql, $bindings, $time) {
//
});
}
/**
* サービスプロバイダーの登録
*
* @return void
*/
public function register()
{
//
}
}
データベーストランザクションDatabase Transactions
一連の操作をデータベーストランザクション内で実行するには、DB
ファサードのtransaction
メソッドを使用してください。トランザクション「クロージャー」の中で例外が投げられると、トランザクションは自動的にロールバックされます。「クロージャー」が正しく実行されると、自動的にコミットされます。transaction
メソッドを使用すれば、ロールバックやコミットを手動で行う必要はありません。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::transaction(function () {
DB::table('users')->update(['votes' => 1]);
DB::table('posts')->delete();
});
手動トランザクション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();
注目:
DB
ファサードのトランザクションメソッドにより、クエリービルダーとEloquent ORMのトランザクションもコントロールできます。Note: Using theDB
facade's transaction methods also controls transactions for the query builder[/docs/{{version}}/queries] and Eloquent ORM[/docs/{{version}}/eloquent].
複数接続の使用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();