Readouble

Laravel 5.0 データベースの基本的な使用法

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

設定配列にreadwrite、2つのキーが追加されたことに注目して下さい。2つのキーともhostというキーを一つ持っています。readwrite接続時の残りのデータベースオプションは、メインのmysql配列からマージされます。ですから、readwriteの配列には、メインの配列の値をオーバーライドしたいものだけ指定してください。この場合、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.

もしくは結合に名前を指定し、クエリーを実行することもできます。You may also execute a query using named bindings:

$results = DB::select('select * from users where id = :id', ['id' => 1]);

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');

注目: updatedelete文はその操作により影響を受けるレコード数をリターンします。Note: The update and delete 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 the transaction 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

現在のリクエスト中に実行された全クエリーをメモリーにログしておくことも可能です。大量の行を挿入するようなケースでは、これにより大量のメモリーが使用されることに注意を払ってください。ログを有効にするには、enableQueryLogメソッドを使用してください。Laravel can optionally log in memory all queries that have been run for the current request. Be aware that in some cases, such as when inserting a large number of rows, this can cause the application to use excess memory. To enable the log, you may use the enableQueryLog method:

DB::connection()->enableQueryLog();

実行済みのクエリーの配列を取得するために、getQueryLogメソッドが使用できます。To get an array of the executed queries, you may use the getQueryLog method:

$queries = DB::getQueryLog();

章選択

Artisan CLI

設定

明暗テーマ
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!…]形式の挿入削除行の表示形式です。

テストコード表示
両コード表示
Pestのみ表示
PHPUnitのみ表示
和文変換

対象文字列と置換文字列を半角スペースで区切ってください。(最大5組各10文字まで)

本文フォント

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

コードフォント

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

保存内容リセット

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

ヘッダー項目移動

キーボード操作