Readouble

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

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

- MySQL - PostgreSQL - SQLite - SQL Server

設定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. 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

SQLiteで外部キー制約を有効にするには、config/database.php設定ファイルにforeign_key_constraintsオプションを追加します。To enable foreign key constraints for SQLite connections, you should add the foreign_key_constraints option to your config/database.php configuration file:

'sqlite' => [
    // ...
    'foreign_key_constraints' => true,
],

URLを使用したデータベース設定Configuration Using URLs

通常、データベース接続はhostdatabaseusernamepasswordなどのような複数の設定値を用いて設定します。これらの各設定値は、対応する環境変数を持っています。つまり、実働サーバ上でデータベース接続情報を設定する場合に、多くの環境変数を管理する必要があります。Typically, database connections are configured using multiple configuration values such as host, database, username, password, etc. Each of these configuration values has its own corresponding environment variable. This means that when configuring your database connection information on a production server, you need to manage several environment variables.

Herokuのようなマネージドデータベースのプロバイダーでは、一つの文字列の中にデータベースの接続状を全部含めたデータベース"URL"を提供しています。例えば、サンプルのデータベースURLは次のようになります。Some managed database providers such as Heroku provide a single database "URL" that contains all of the connection information for the database in a single string. An example database URL may look something like the following:

mysql://root:password@127.0.0.1/forge?charset=UTF-8

こうしたURLは通常、次のような標準的なスキーマ規約に従います。These URLs typically follow a standard schema convention:

driver://username:password@host:port/database?options

これに対応するため、Laravelは複数の接続オプションを使い、データベースの設定を変更可能なURLをサポートしています。(DATABASE_URL環境変数に対応している)url設定オプションが存在する場合は、データベース接続と接続情報を取り出し、接続に使用します。For convenience, Laravel supports these URLs as an alternative to configuring your database with multiple configuration options. If the url (or corresponding DATABASE_URL environment variable) configuration option is present, it will be used to extract the database connection and credential information.

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',
            '196.168.1.2',
        ],
    ],
    'write' => [
        'host' => [
            '196.168.1.3',
         ],
    ],
    'sticky'    => true,
    'driver'    => 'mysql',
    'database'  => 'database',
    'username'  => 'root',
    'password'  => '',
    'charset'   => 'utf8mb4',
    'collation' => 'utf8mb4_unicode_ci',
    'prefix'    => '',
],

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

readwriteの配列には、メインの配列の値をオーバーライドしたいものだけ指定してください。この場合、192.168.1.1は"read"接続に利用され、一方192.168.1.3が"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.3 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ファサードは 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, 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 register()
    {
        //
    }

    /**
     * 全アプリケーションサービスの初期起動
     *
     * @return void
     */
    public function boot()
    {
        DB::listen(function ($query) {
            // $query->sql
            // $query->bindings
            // $query->time
        });
    }
}

データベーストランザクション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();

lightbulb">Tip!! DBファサードのトランザクションメソッドは、クエリビルダEloquent ORMのトランザクションを両方共にコントロールします。{tip} The DB facade's transaction methods control the transactions for both the query builder[/docs/{{version}}/queries] and Eloquent ORM[/docs/{{version}}/eloquent].

章選択

設定

明暗テーマ
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に保存してある設定項目をすべて削除し、デフォルト状態へ戻します。

ヘッダー項目移動

キーボード操作