Readouble

Laravel 5.2 データベース:利用開始

イントロダクション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.

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

SQLサーバ設定SQL Server Configuration

LaravelはSQLサーバを標準でサポートしていますが、データベースへの接続設定を追加する必要があります。Laravel supports SQL Server out of the box; however, you will need to add the connection configuration for the database:

'sqlsrv' => [
    'driver' => 'sqlsrv',
    'host' => env('DB_HOST', 'localhost'),
    'database' => env('DB_DATABASE', 'forge'),
    'username' => env('DB_USERNAME', 'forge'),
    'password' => env('DB_PASSWORD', ''),
    'charset' => 'utf8',
    'prefix' => '',
],

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'    => '',
],

設定配列にreadwrite、2つのキーが追加されたことに注目して下さい。2つのキーともhostというキーを一つ持っています。readwrite接続時の残りのデータベースオプションは、メインの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.

ですから、readwriteの配列には、メインの配列の値をオーバーライドしたいものだけ指定してください。この場合、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ファサードは selectupdateinsertdeletestatementのクエリタイプごとにメソッドを用意しています。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 ($query) {
            // $query->sql
            // $query->bindings
            // $query->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 the DB 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();

章選択

設定

明暗テーマ
light_mode
dark_mode
brightness_auto システム設定に合わせる
テーマ選択
photo_size_select_actual デフォルト
photo_size_select_actual モノクローム(白黒)
photo_size_select_actual Solarized風
photo_size_select_actual GitHub風(青ベース)
photo_size_select_actual Viva(黄緑ベース)
photo_size_select_actual Happy(紫ベース)
photo_size_select_actual Mint(緑ベース)
コードハイライトテーマ選択

明暗テーマごとに、コードハイライトのテーマを指定できます。

テーマ配色確認
スクリーン表示幅
640px
80%
90%
100%

768px以上の幅があるときのドキュメント部分表示幅です。

インデント
無し
1rem
2rem
3rem
原文確認
原文を全行表示
原文を一行ずつ表示
使用しない

※ 段落末のEボタンへカーソルオンで原文をPopupします。

Diff表示形式
色分けのみで区別
行頭の±で区別
削除線と追記で区別

※ [tl!…]形式の挿入削除行の表示形式です。

Pagination和文
ペジネーション
ペギネーション
ページネーション
ページ付け
Scaffold和文
スカフォールド
スキャフォールド
型枠生成
本文フォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

コードフォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

保存内容リセット

localStrageに保存してある設定項目をすべて削除し、デフォルト状態へ戻します。

ヘッダー項目移動

キーボード操作