Readouble

Laravel 5.8 データベース:クエリビルダ

イントロダクションIntroduction

データベースクエリビルダはスラスラと書ける(fluent)便利なインターフェイスで、クエリを作成し実行するために使用します。アプリケーションで行われるほとんどのデーターベース操作が可能で、サポートしている全データベースシステムに対し使用できます。Laravel's database query builder provides a convenient, fluent interface to creating and running database queries. It can be used to perform most database operations in your application and works on all supported database systems.

LaravelクエリビルダはアプリケーションをSQLインジェクション攻撃から守るために、PDOパラメーターによるバインディングを使用します。バインドする文字列をクリーンにしてから渡す必要はありません。The Laravel query builder uses PDO parameter binding to protect your application against SQL injection attacks. There is no need to clean strings being passed as bindings.

Note: note PDOはカラム名によるバインドをサポートしていません。そのため、"order by"カラムなどを含め、クエリに直接カラム名を参照するユーザー入力を許してはいけません。クエリに対する特定のカラムの選択をユーザーに許す場合は、許可するカラムのホワイトリストを用意し、常にカラム名を確認してください。{note} PDO does not support binding column names. Therefore, you should never allow user input to dictate the column names referenced by your queries, including "order by" columns, etc. If you must allow the user to select certain columns to query against, always validate the column names against a white-list of allowed columns.

結果の取得Retrieving Results

全レコードの取得Retrieving All Rows From A Table

クエリを書くにはDBファサードのtableメソッドを使います。tableメソッドは指定したテーブルに対するクエリビルダインスタンスを返します。これを使いクエリに制約を加え、最終的な結果を取得するチェーンを繋げます。次に、最終的な結果をgetで取得します。You may use the table method on the DB facade to begin a query. The table method returns a fluent query builder instance for the given table, allowing you to chain more constraints onto the query and then finally get the results using the get method:

<?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::table('users')->get();

        return view('user.index', ['users' => $users]);
    }
}

getメソッドは、PHPのstdClassオブジェクトのインスタンスを結果として含む、Illuminate\Support\Collectionを返します。各カラムの値は、オブジェクトのプロパティとしてアクセスできます。The get method returns an Illuminate\Support\Collection containing the results where each result is an instance of the PHP stdClass object. You may access each column's value by accessing the column as a property of the object:

foreach ($users as $user) {
    echo $user->name;
}

テーブルから1カラム/1レコード取得Retrieving A Single Row / Column From A Table

データベーステーブルから1レコードのみ取得する必要がある場合は、firstメソッドを使います。このメソッドはstdClassオブジェクトを返します。If you just need to retrieve a single row from the database table, you may use the first method. This method will return a single stdClass object:

$user = DB::table('users')->where('name', 'John')->first();

echo $user->name;

全カラムは必要ない場合、valueメソッドにより一つの値のみ取得できます。このメソッドはカラムの値を直接返します。If you don't even need an entire row, you may extract a single value from a record using the value method. This method will return the value of the column directly:

$email = DB::table('users')->where('name', 'John')->value('email');

idカラム値により1行取得する場合は、findメソッドを使用してください。To retrieve a single row by its id column value, use the find method:

$user = DB::table('users')->find(3);

カラム値をリストで取得Retrieving A List Of Column Values

単一カラムの値をコレクションで取得したい場合はpluckメソッドを使います。以下の例では役割名(title)をコレクションで取得しています。If you would like to retrieve a Collection containing the values of a single column, you may use the pluck method. In this example, we'll retrieve a Collection of role titles:

$titles = DB::table('roles')->pluck('title');

foreach ($titles as $title) {
    echo $title;
}

取得コレクションのキーカラムを指定することもできます。You may also specify a custom key column for the returned Collection:

$roles = DB::table('roles')->pluck('title', 'name');

foreach ($roles as $name => $title) {
    echo $title;
}

結果の分割Chunking Results

数千のデータベースレコードを扱う場合はchunkメソッドの使用を考慮してください。このメソッドは一度に小さな「かたまり(chunk)」で結果を取得し、このチャンクは処理のために「クロージャ」に渡されます。このメソッドは数千のレコードを処理するArtisanコマンドを書くときに便利です。usersレコード全体から一度に100レコードずつチャンクを処理する例を見てください。If you need to work with thousands of database records, consider using the chunk method. This method retrieves a small chunk of the results at a time and feeds each chunk into a Closure for processing. This method is very useful for writing Artisan commands[/docs/{{version}}/artisan] that process thousands of records. For example, let's work with the entire users table in chunks of 100 records at a time:

DB::table('users')->orderBy('id')->chunk(100, function ($users) {
    foreach ($users as $user) {
        //
    }
});

クロージャからfalseを返すとチャンクの処理を中断できます。You may stop further chunks from being processed by returning false from the Closure:

DB::table('users')->orderBy('id')->chunk(100, function ($users) {
    // レコードの処理…

    return false;
});

結果をチャンクしつつデータベースレコードを更新すると、チャンク結果が意図しない変化を起こす可能性があります。そのため、チャンク結果を更新する場合は、常に代わりのchunkByIdメソッドを使用するのが最善です。このメソッドは自動的にレコードの主キーに基づいて結果を自動的にページ割りします。If you are updating database records while chunking results, your chunk results could change in unexpected ways. So, when updating records while chunking, it is always best to use the chunkById method instead. This method will automatically paginate the results based on the record's primary key:

DB::table('users')->where('active', false)
    ->chunkById(100, function ($users) {
        foreach ($users as $user) {
            DB::table('users')
                ->where('id', $user->id)
                ->update(['active' => true]);
        }
    });

Note: note chunkのコールバックの中で、レコードを更新/削除することにより主キーや外部キーが変化すると、chunkクエリに影響を及ぼします。分割結果にレコードが含まれない可能性が起きます。{note} When updating or deleting records inside the chunk callback, any changes to the primary key or foreign keys could affect the chunk query. This could potentially result in records not being included in the chunked results.

集計Aggregates

またクエリビルダはcountmaxminavgsumなど多くの集計メソッドを提供しています。クエリを制約した後にこれらのメソッドを使うことも可能です。The query builder also provides a variety of aggregate methods such as count, max, min, avg, and sum. You may call any of these methods after constructing your query:

$users = DB::table('users')->count();

$price = DB::table('orders')->max('price');

これらのメソッドをクエリを構築するために他の節と組み合わせて使用できます。You may combine these methods with other clauses:

$price = DB::table('orders')
                ->where('finalized', 1)
                ->avg('price');

レコード存在の判定Determining If Records Exist

クエリの制約にマッチするレコードが存在するかを調べるため、countメソッドを使用する代わりに、existsdoesntExistメソッドを使うこともできます。Instead of using the count method to determine if any records exist that match your query's constraints, you may use the exists and doesntExist methods:

return DB::table('orders')->where('finalized', 1)->exists();

return DB::table('orders')->where('finalized', 1)->doesntExist();

SELECTSelects

SELECT節の指定Specifying A Select Clause

常にデータベースレコードの全カラムは必要ではないでしょう。クエリのselect節をselectメソッドで指定できます。You may not always want to select all columns from a database table. Using the select method, you can specify a custom select clause for the query:

$users = DB::table('users')->select('name', 'email as user_email')->get();

distinctメソッドで重複行をまとめた結果を返すように強制できます。The distinct method allows you to force the query to return distinct results:

$users = DB::table('users')->distinct()->get();

既にクエリビルダインスタンスがあり、select節にカラムを追加したい場合はaddSelectメソッドを使ってください。If you already have a query builder instance and you wish to add a column to its existing select clause, you may use the addSelect method:

$query = DB::table('users')->select('name');

$users = $query->addSelect('age')->get();

SQL文Raw Expressions

時々、クエリの中でSQLを直接使用したいことがあります。エスケープなしのSQLを使用する場合はDB::rawメソッドを使用します。Sometimes you may need to use a raw expression in a query. To create a raw expression, you may use the DB::raw method:

$users = DB::table('users')
                     ->select(DB::raw('count(*) as user_count, status'))
                     ->where('status', '<>', 1)
                     ->groupBy('status')
                     ->get();

Note: note rawメソッドはクエリを文字列として挿入するため、SQLインジェクションの脆弱性を生まないように十分気をつけてください。{note} Raw statements will be injected into the query as strings, so you should be extremely careful to not create SQL injection vulnerabilities.

rawメソッドRaw Methods

DB::rawを使用する代わりに、クエリの様々な箇所へSQL文を挿入する、以降のメソッドも使用できます。Instead of using DB::raw, you may also use the following methods to insert a raw expression into various parts of your query.

selectRawselectRaw

selectRawメソッドは、select(DB::raw(...))に置き換えて使用できます。このメソッドは、第2引数へバインド値の配列を指定することも可能です。The selectRaw method can be used in place of select(DB::raw(...)). This method accepts an optional array of bindings as its second argument:

$orders = DB::table('orders')
                ->selectRaw('price * ? as price_with_tax', [1.0825])
                ->get();

whereRaw / orWhereRawwhereRaw / orWhereRaw

whereRaworWhereRawメソッドは、クエリへwhere節を挿入できます。これらのメソッドは、第2引数にバインド値の配列を指定することもできます。The whereRaw and orWhereRaw methods can be used to inject a raw where clause into your query. These methods accept an optional array of bindings as their second argument:

$orders = DB::table('orders')
                ->whereRaw('price > IF(state = "TX", ?, 100)', [200])
                ->get();

havingRaw / orHavingRawhavingRaw / orHavingRaw

havingRaworHavingRawメソッドは、文字列をhaving節の値として指定するために使用します。両メソッドは、第2引数にオプションとして、バインドの配列を渡すことができます。The havingRaw and orHavingRaw methods may be used to set a raw string as the value of the having clause. These methods accept an optional array of bindings as their second argument:

$orders = DB::table('orders')
                ->select('department', DB::raw('SUM(price) as total_sales'))
                ->groupBy('department')
                ->havingRaw('SUM(price) > ?', [2500])
                ->get();

orderByRaworderByRaw

orderByRawメソッドは、文字列をorder by節の値として指定するために使用します。The orderByRaw method may be used to set a raw string as the value of the order by clause:

$orders = DB::table('orders')
                ->orderByRaw('updated_at - created_at DESC')
                ->get();

JOINJoins

INNER JOIN文Inner Join Clause

さらにクエリビルダはJOIN文を書くためにも使用できます。基本的な"INNER JOIN"を実行するには、クエリビルダインスタンスにjoinメソッドを使ってください。joinメソッドの第1引数は結合したいテーブル名、それ以降の引数にはJOIN時のカラムの制約条件を指定します。一つのクエリで複数のテーブルを結合することもできます。The query builder may also be used to write join statements. To perform a basic "inner join", you may use the join method on a query builder instance. The first argument passed to the join method is the name of the table you need to join to, while the remaining arguments specify the column constraints for the join. You can even join to multiple tables in a single query:

$users = DB::table('users')
            ->join('contacts', 'users.id', '=', 'contacts.user_id')
            ->join('orders', 'users.id', '=', 'orders.user_id')
            ->select('users.*', 'contacts.phone', 'orders.price')
            ->get();

LEFT JOIN/RIGHT JOIN文Left Join / Right Join Clause

"INNER JOIN"の代わりに"LEFT JOIN"か"RIGHT JOIN"を実行したい場合は、leftJoinrightJoinメソッドを使います。これらのメソッドの使い方はjoinメソッドと同じです。If you would like to perform a "left join" or "right join" instead of an "inner join", use the leftJoin or rightJoin methods. These methods have the same signature as the join method:

$users = DB::table('users')
            ->leftJoin('posts', 'users.id', '=', 'posts.user_id')
            ->get();

$users = DB::table('users')
            ->rightJoin('posts', 'users.id', '=', 'posts.user_id')
            ->get();

クロスジョイン文Cross Join Clause

「クロスジョイン」を実行するときは、接合したいテーブル名を指定し、crossJoinメソッドを使ってください。クロスジョインにより、最初のテーブルと指定したテーブルとの、デカルト積を生成します。To perform a "cross join" use the crossJoin method with the name of the table you wish to cross join to. Cross joins generate a cartesian product between the first table and the joined table:

$users = DB::table('sizes')
            ->crossJoin('colours')
            ->get();

上級のJOIN文Advanced Join Clauses

さらに上級なJOIN節を指定することもできます。そのためにはjoinメソッドの第2引数に「クロージャ」を指定します。その「クロージャ」はJOIN節に制約を指定できるようにするJoinClauseオブジェクトを受け取ります。You may also specify more advanced join clauses. To get started, pass a Closure as the second argument into the join method. The Closure will receive a JoinClause object which allows you to specify constraints on the join clause:

DB::table('users')
        ->join('contacts', function ($join) {
            $join->on('users.id', '=', 'contacts.user_id')->orOn(...);
        })
        ->get();

JOINに"where"節を使用したい場合はjoinの中でwhereorWhereを使用して下さい。2つのカラムを比べる代わりに、これらのメソッドは値とカラムを比較します。If you would like to use a "where" style clause on your joins, you may use the where and orWhere methods on a join. Instead of comparing two columns, these methods will compare the column against a value:

DB::table('users')
        ->join('contacts', function ($join) {
            $join->on('users.id', '=', 'contacts.user_id')
                 ->where('contacts.user_id', '>', 5);
        })
        ->get();

サブクエリのJOINSub-Query Joins

サブクエリへクエリをJOINするために、joinSubleftJoinSubrightJoinSubメソッドを利用できます。各メソッドは3つの引数を取ります。サブクエリ、テーブルのエイリアス、関連するカラムを定義するクロージャです。You may use the joinSub, leftJoinSub, and rightJoinSub methods to join a query to a sub-query. Each of these methods receive three arguments: the sub-query, its table alias, and a Closure that defines the related columns:

$latestPosts = DB::table('posts')
                   ->select('user_id', DB::raw('MAX(created_at) as last_post_created_at'))
                   ->where('is_published', true)
                   ->groupBy('user_id');

$users = DB::table('users')
        ->joinSub($latestPosts, 'latest_posts', function ($join) {
            $join->on('users.id', '=', 'latest_posts.user_id');
        })->get();

UNIONUnions

クエリビルダは2つのクエリを結合(union)させる手軽な手法を提供します。たとえば最初にクエリを作成し、その後に2つ目のクエリを結合するためにunionメソッドを使います。The query builder also provides a quick way to "union" two queries together. For example, you may create an initial query and use the union method to union it with a second query:

$first = DB::table('users')
            ->whereNull('first_name');

$users = DB::table('users')
            ->whereNull('last_name')
            ->union($first)
            ->get();

lightbulb">Tip!! unionと同じ使い方のunionAllメソッドも使えます。{tip} The unionAll method is also available and has the same method signature as union.

WHERE節Where Clauses

単純なWHERE節Simple Where Clauses

where節をクエリに追加するには、クエリビルダインスタンスのwhereメソッドを使います。基本的なwhereの呼び出しでは3つの引数を使います。第1引数はカラム名です。第2引数はデータベースがサポートしているオペレーターです。第3引数はカラムに対して比較する値です。You may use the where method on a query builder instance to add where clauses to the query. The most basic call to where requires three arguments. The first argument is the name of the column. The second argument is an operator, which can be any of the database's supported operators. Finally, the third argument is the value to evaluate against the column.

例として、"votes"カラムの値が100と等しいレコードのクエリを見てください。For example, here is a query that verifies the value of the "votes" column is equal to 100:

$users = DB::table('users')->where('votes', '=', 100)->get();

カラムが指定値と等しいかを比べたい場合は利便性を良くするため、whereメソッドの第2引数に値をそのまま指定できます。For convenience, if you want to verify that a column is equal to a given value, you may pass the value directly as the second argument to the where method:

$users = DB::table('users')->where('votes', 100)->get();

where文を書くときには、その他いろいろなオペレータも使えます。You may use a variety of other operators when writing a where clause:

$users = DB::table('users')
                ->where('votes', '>=', 100)
                ->get();

$users = DB::table('users')
                ->where('votes', '<>', 100)
                ->get();

$users = DB::table('users')
                ->where('name', 'like', 'T%')
                ->get();

whereに配列で条件を渡すこともできます。You may also pass an array of conditions to the where function:

$users = DB::table('users')->where([
    ['status', '=', '1'],
    ['subscribed', '<>', '1'],
])->get();

OR節Or Statements

WHEREの結合にチェーンでor節をクエリに追加できます。orWhereメソッドはwhereメソッドと同じ引数を受け付けます。You may chain where constraints together as well as add or clauses to the query. The orWhere method accepts the same arguments as the where method:

$users = DB::table('users')
                    ->where('votes', '>', 100)
                    ->orWhere('name', 'John')
                    ->get();

その他のWHERE節Additional Where Clauses

whereBetween / orWhereBetweenwhereBetween / orWhereBetween

whereBetweenメソッドはカラムの値が2つの値の間である条件を加えます。The whereBetween method verifies that a column's value is between two values:

$users = DB::table('users')
                    ->whereBetween('votes', [1, 100])->get();

whereNotBetween / orWhereNotBetweenwhereNotBetween / orWhereNotBetween

whereNotBetweenメソッドは、カラムの値が2つの値の間ではない条件を加えます。The whereNotBetween method verifies that a column's value lies outside of two values:

$users = DB::table('users')
                    ->whereNotBetween('votes', [1, 100])
                    ->get();

whereIn / whereNotIn / orWhereIn / orWhereNotInwhereIn / whereNotIn / orWhereIn / orWhereNotIn

whereInメソッドは指定した配列の中にカラムの値が含まれている条件を加えます。The whereIn method verifies that a given column's value is contained within the given array:

$users = DB::table('users')
                    ->whereIn('id', [1, 2, 3])
                    ->get();

whereNotInメソッドはカラムの値が指定した配列の中に含まれていない条件を加えます。The whereNotIn method verifies that the given column's value is not contained in the given array:

$users = DB::table('users')
                    ->whereNotIn('id', [1, 2, 3])
                    ->get();

whereNull / whereNotNull / orWhereNull / orWhereNotNullwhereNull / whereNotNull / orWhereNull / orWhereNotNull

whereNullメソッドは指定したカラムの値がNULLである条件を加えます。The whereNull method verifies that the value of the given column is NULL:

$users = DB::table('users')
                    ->whereNull('updated_at')
                    ->get();

whereNotNullメソッドは指定したカラムの値がNULLでない条件を加えます。The whereNotNull method verifies that the column's value is not NULL:

$users = DB::table('users')
                    ->whereNotNull('updated_at')
                    ->get();

whereDate / whereMonth / whereDay / whereYear / whereTimewhereDate / whereMonth / whereDay / whereYear / whereTime

whereDateメソッドはカラム値を日付と比較する時に使用します。The whereDate method may be used to compare a column's value against a date:

$users = DB::table('users')
                ->whereDate('created_at', '2016-12-31')
                ->get();

whereMonthメソッドはカラム値と、ある年の指定した月とを比較します。The whereMonth method may be used to compare a column's value against a specific month of a year:

$users = DB::table('users')
                ->whereMonth('created_at', '12')
                ->get();

whereDayメソッドはカラム値と、ある月の指定した日とを比べます。The whereDay method may be used to compare a column's value against a specific day of a month:

$users = DB::table('users')
                ->whereDay('created_at', '31')
                ->get();

whereYearメソッドはカラム値と、指定した年とを比べます。The whereYear method may be used to compare a column's value against a specific year:

$users = DB::table('users')
                ->whereYear('created_at', '2016')
                ->get();

whereTimeメソッドはカラム地と、指定した時間を比較します。The whereTime method may be used to compare a column's value against a specific time:

$users = DB::table('users')
                ->whereTime('created_at', '=', '11:20:45')
                ->get();

whereColumn / orWhereColumnwhereColumn / orWhereColumn

whereColumnメソッドは2つのカラムが同値である確認をするのに使います。The whereColumn method may be used to verify that two columns are equal:

$users = DB::table('users')
                ->whereColumn('first_name', 'last_name')
                ->get();

メソッドに比較演算子を追加指定することもできます。You may also pass a comparison operator to the method:

$users = DB::table('users')
                ->whereColumn('updated_at', '>', 'created_at')
                ->get();

whereColumnへ配列により複数の条件を渡すこともできます。各条件はandオペレータでつなげられます。The whereColumn method can also be passed an array of multiple conditions. These conditions will be joined using the and operator:

$users = DB::table('users')
                ->whereColumn([
                    ['first_name', '=', 'last_name'],
                    ['updated_at', '>', 'created_at']
                ])->get();

パラメータのグループ分けParameter Grouping

時には、"WHERE EXISTS"節やグループにまとめたパラーメーターのネストのような、上級のWHERE節を作成する必要が起きます。Laravelクエリビルダはこれらもうまく処理できます。手始めに、カッコで制約をまとめる例を見てください。Sometimes you may need to create more advanced where clauses such as "where exists" clauses or nested parameter groupings. The Laravel query builder can handle these as well. To get started, let's look at an example of grouping constraints within parenthesis:

DB::table('users')
            ->where('name', '=', 'John')
            ->where(function ($query) {
                $query->where('votes', '>', 100)
                      ->orWhere('title', '=', 'Admin');
            })
            ->get();

ご覧の通り、Whereメソッドに渡している「クロージャ」が、クエリビルダのグルーピングを指示しています。生成するSQLの括弧内で展開される制約を指定できるように、「クロージャ」はクエリビルダのインスタンスを受け取ります。As you can see, passing a Closure into the where method instructs the query builder to begin a constraint group. The Closure will receive a query builder instance which you can use to set the constraints that should be contained within the parenthesis group. The example above will produce the following SQL:

select * from users where name = 'John' and (votes > 100 or title = 'Admin')

lightbulb">Tip!! グローバルスコープが適用されるときに、予想外の動作を防ぐために、orWhereコールは常にまとめてください。{tip} You should always group orWhere calls in order to avoid unexpected behavior when global scopes are applied.

Where Exists節Where Exists Clauses

whereExistsメソッドはWHERE EXISTSのSQLを書けるように用意しています。whereExistsメソッドは引数に「クロージャ」を取り、"EXISTS"節の中に置かれるクエリを定義するためのクエリビルダを受け取ります。The whereExists method allows you to write where exists SQL clauses. The whereExists method accepts a Closure argument, which will receive a query builder instance allowing you to define the query that should be placed inside of the "exists" clause:

DB::table('users')
            ->whereExists(function ($query) {
                $query->select(DB::raw(1))
                      ->from('orders')
                      ->whereRaw('orders.user_id = users.id');
            })
            ->get();

上のクエリは以下のSQLを生成します。The query above will produce the following SQL:

select * from users
where exists (
    select 1 from orders where orders.user_id = users.id
)

JSON WHERE節JSON Where Clauses

Laravelはデータベース上のJSONタイプをサポートするカラムに対するクエリに対応しています。現在、MySQL5.7とPostgreSQL、SQL Server2016、SQLite3.9.0(JSON1拡張使用時)に対応しています。JSONカラムをクエリするには->オペレータを使ってください。Laravel also supports querying JSON column types on databases that provide support for JSON column types. Currently, this includes MySQL 5.7, PostgreSQL, SQL Server 2016, and SQLite 3.9.0 (with the JSON1 extension[https://www.sqlite.org/json1.html]). To query a JSON column, use the -> operator:

$users = DB::table('users')
                ->where('options->language', 'en')
                ->get();

$users = DB::table('users')
                ->where('preferences->dining->meal', 'salad')
                ->get();

JSON配列をクエリするには、whereJsonContainsを使います。(SQLiteではサポートされていません)You may use whereJsonContains to query JSON arrays (not supported on SQLite):

$users = DB::table('users')
                ->whereJsonContains('options->languages', 'en')
                ->get();

MySQLとPostgreSQLでは、whereJsonContainsで複数の値をサポートしています。MySQL and PostgreSQL support whereJsonContains with multiple values:

$users = DB::table('users')
                ->whereJsonContains('options->languages', ['en', 'de'])
                ->get();

JSON配列を長さでクエリするには、whereJsonLengthを使います。You may use whereJsonLength to query JSON arrays by their length:

$users = DB::table('users')
                ->whereJsonLength('options->languages', 0)
                ->get();

$users = DB::table('users')
                ->whereJsonLength('options->languages', '>', 1)
                ->get();

順序、グループ分け、制限、オフセットOrdering, Grouping, Limit, & Offset

orderByorderBy

orderByメソッドは指定したカラムでクエリ結果をソートします。orderByメソッドの最初の引数はソート対象のカラムで、第2引数はソートの昇順(asc)と降順(desc)をコントロールします。The orderBy method allows you to sort the result of the query by a given column. The first argument to the orderBy method should be the column you wish to sort by, while the second argument controls the direction of the sort and may be either asc or desc:

$users = DB::table('users')
                ->orderBy('name', 'desc')
                ->get();

latest/oldestlatest / oldest

latestoldestメソッドにより、データの結果を簡単に整列できます。デフォルトで、結果はcreated_atカラムによりソートされます。ソートキーとしてカラム名を渡すこともできます。The latest and oldest methods allow you to easily order results by date. By default, result will be ordered by the created_at column. Or, you may pass the column name that you wish to sort by:

$user = DB::table('users')
                ->latest()
                ->first();

inRandomOrderinRandomOrder

inRandomOrderメソッドはクエリ結果をランダムな順番にしたい時に使用します。たとえば、以下のコードはランダムにユーザーを一人取得します。The inRandomOrder method may be used to sort the query results randomly. For example, you may use this method to fetch a random user:

$randomUser = DB::table('users')
                ->inRandomOrder()
                ->first();

groupBy / havinggroupBy / having

groupByhavingメソッドはクエリ結果をグループにまとめるために使用します。havingメソッドはwhereメソッドと似た使い方です。The groupBy and having methods may be used to group the query results. The having method's signature is similar to that of the where method:

$users = DB::table('users')
                ->groupBy('account_id')
                ->having('account_id', '>', 100)
                ->get();

複数カラムによるグループ化のため、groupByメソッドに複数の引数を指定できます。You may pass multiple arguments to the groupBy method to group by multiple columns:

$users = DB::table('users')
                ->groupBy('first_name', 'status')
                ->having('account_id', '>', 100)
                ->get();

より上級なhaving文については、havingRawメソッドを参照してください。For more advanced having statements, see the havingRaw[#raw-methods] method.

skip / takeskip / take

クエリから限られた(LIMIT)数のレコードを受け取ったり、結果から指定した件数を飛ばしたりするには、skiptakeメソッドを使います。To limit the number of results returned from the query, or to skip a given number of results in the query, you may use the skip and take methods:

$users = DB::table('users')->skip(10)->take(5)->get();

別の方法として、limitoffsetメソッドも使用できます。Alternatively, you may use the limit and offset methods:

$users = DB::table('users')
                ->offset(10)
                ->limit(5)
                ->get();

条件節Conditional Clauses

ある条件がtrueの場合の時のみ、クエリへ特定の文を適用したい場合があります。例えば特定の入力値がリクエストに含まれている場合に、where文を適用する場合です。whenメソッドで実現できます。Sometimes you may want clauses to apply to a query only when something else is true. For instance you may only want to apply a where statement if a given input value is present on the incoming request. You may accomplish this using the when method:

$role = $request->input('role');

$users = DB::table('users')
                ->when($role, function ($query, $role) {
                    return $query->where('role_id', $role);
                })
                ->get();

whenメソッドは、第1引数がtrueの時のみ、指定されたクロージャを実行します。最初の引数がfalseの場合、クロージャを実行しません。The when method only executes the given Closure when the first parameter is true. If the first parameter is false, the Closure will not be executed.

whenメソッドの第3引数に別のクロージャを渡せます。このクロージャは、最初の引数の評価がfalseであると実行されます。この機能をどう使うかを確認するため、クエリのデフォルトソートを設定してみましょう。You may pass another Closure as the third parameter to the when method. This Closure will execute if the first parameter evaluates as false. To illustrate how this feature may be used, we will use it to configure the default sorting of a query:

$sortBy = null;

$users = DB::table('users')
                ->when($sortBy, function ($query, $sortBy) {
                    return $query->orderBy($sortBy);
                }, function ($query) {
                    return $query->orderBy('name');
                })
                ->get();

INSERTInserts

クエリビルダは、データベーステーブルにレコードを挿入するためのinsertメソッドを提供しています。insertメソッドは挿入するカラム名と値の配列を引数に取ります。The query builder also provides an insert method for inserting records into the database table. The insert method accepts an array of column names and values:

DB::table('users')->insert(
    ['email' => 'john@example.com', 'votes' => 0]
);

配列の配列をinsertに渡して呼び出すことで、テーブルにたくさんのレコードを一度にまとめて挿入できます。You may even insert several records into the table with a single call to insert by passing an array of arrays. Each array represents a row to be inserted into the table:

DB::table('users')->insert([
    ['email' => 'taylor@example.com', 'votes' => 0],
    ['email' => 'dayle@example.com', 'votes' => 0]
]);

insertOrIgnoreメソッドは、データベースにレコードを挿入する際、重複レコードエラーを無視します。The insertOrIgnore method will ignore duplicate record errors while inserting records into the database:

DB::table('users')->insertOrIgnore([
    ['id' => 1, 'email' => 'taylor@example.com'],
    ['id' => 2, 'email' => 'dayle@example.com']
]);

自動増分IDAuto-Incrementing IDs

テーブルが自動増分IDを持っている場合、insertGetIdメソッドを使うとレコードを挿入し、そのレコードのIDを返してくれます。If the table has an auto-incrementing id, use the insertGetId method to insert a record and then retrieve the ID:

$id = DB::table('users')->insertGetId(
    ['email' => 'john@example.com', 'votes' => 0]
);

Note: note PostgreSQLでinsertGetIdメソッドを使う場合、自動増分カラム名はidである必要があります。他の「シーケンス」からIDを取得したい場合は、insertGetIdメソッドの第2引数へカラム名を指定してください。{note} When using PostgreSQL the insertGetId method expects the auto-incrementing column to be named id. If you would like to retrieve the ID from a different "sequence", you may pass the column name as the second parameter to the insertGetId method.

UPDATEUpdates

データベースへレコードを挿入するだけでなく、存在しているレコードをupdateメソッドで更新することもできます。updateメソッドはinsertメソッドと同様に、更新対象のカラムのカラム名と値の配列を引数に受け取ります。更新するクエリをwhere節を使って制約することもできます。In addition to inserting records into the database, the query builder can also update existing records using the update method. The update method, like the insert method, accepts an array of column and value pairs containing the columns to be updated. You may constrain the update query using where clauses:

DB::table('users')
            ->where('id', 1)
            ->update(['votes' => 1]);

UPDATEかINSERTUpdate Or Insert

データベースへ一致するレコードが存在している場合は更新し、一致するレコードがない場合は新規追加したいことも起きます。このようなシナリオでは、updateOrInsertメソッドが使えます。updateOrInsertメソッドは2つの引数を取ります。見つけようとするレコードの条件の配列と、更新するカラム/値のペアの配列です。Sometimes you may want to update an existing record in the database or create it if no matching record exists. In this scenario, the updateOrInsert method may be used. The updateOrInsert method accepts two arguments: an array of conditions by which to find the record, and an array of column and value pairs containing the columns to be updated.

updateOrInsertメソッドは最初の引数のカラム/値ペアを使い、一致するデータベースレコードを見つけようとします。レコードが存在していれば、2つ目の引数の値で更新します。レコードが見つからなければ、両引数をマージした結果で新しいレコードを挿入します。The updateOrInsert method will first attempt to locate a matching database record using the first argument's column and value pairs. If the record exists, it will be updated with the values in the second argument. If the record can not be found, a new record will be inserted with the merged attributes of both arguments:

DB::table('users')
    ->updateOrInsert(
        ['email' => 'john@example.com', 'name' => 'John'],
        ['votes' => '2']
    );

JSONカラムの更新Updating JSON Columns

JSONカラムを更新する場合は、JSONオブジェクト中の適切なキーへアクセスするために、->記法を使用してください。この操作子は、MySQL5.7以上とPostgreSQL9.5以上でサポートしています。When updating a JSON column, you should use -> syntax to access the appropriate key in the JSON object. This operation is supported on MySQL 5.7 and PostgreSQL 9.5 :

DB::table('users')
            ->where('id', 1)
            ->update(['options->enabled' => true]);

増減分Increment & Decrement

クエリビルダは指定したカラムの値を増やしたり、減らしたりするのに便利なメソッドも用意しています。これは短縮記法で、update分で書くのに比べるとより記述的であり、簡潔なインターフェイスを提供しています。The query builder also provides convenient methods for incrementing or decrementing the value of a given column. This is a shortcut, providing a more expressive and terse interface compared to manually writing the update statement.

両方のメソッドともに、最小1つ、更新したいカラムを引数に取ります。オプションの第2引数はそのカラムの増減値を指定します。Both of these methods accept at least one argument: the column to modify. A second argument may optionally be passed to control the amount by which the column should be incremented or decremented:

DB::table('users')->increment('votes');

DB::table('users')->increment('votes', 5);

DB::table('users')->decrement('votes');

DB::table('users')->decrement('votes', 5);

さらに増減操作と一緒に更新する追加のカラムを指定することもできます。You may also specify additional columns to update during the operation:

DB::table('users')->increment('votes', 1, ['name' => 'John']);

DELETEDeletes

クエリビルダはdeleteメソッドで、テーブルからレコードを削除するためにも使用できます。 deleteメソッドを呼び出す前にwhere節を追加し、delete文を制約することもできます。The query builder may also be used to delete records from the table via the delete method. You may constrain delete statements by adding where clauses before calling the delete method:

DB::table('users')->delete();

DB::table('users')->where('votes', '>', 100)->delete();

全レコードを削除し、自動増分のIDを0にリセットするためにテーブルをTRUNCATEしたい場合は、truncateメソッドを使います。If you wish to truncate the entire table, which will remove all rows and reset the auto-incrementing ID to zero, you may use the truncate method:

DB::table('users')->truncate();

悲観的ロックPessimistic Locking

クエリビルダは、SELECT文で「悲観的ロック」を行うための機能をいくつか持っています。SELECT文を実行する間「共有ロック」をかけたい場合は、sharedLockメソッドをクエリに指定して下さい。共有ロックはトランザクションがコミットされるまで、SELECTしている行が更新されることを防ぎます。The query builder also includes a few functions to help you do "pessimistic locking" on your select statements. To run the statement with a "shared lock", you may use the sharedLock method on a query. A shared lock prevents the selected rows from being modified until your transaction commits:

DB::table('users')->where('votes', '>', 100)->sharedLock()->get();

もしくはlockForUpdateメソッドが使えます。占有ロックをかけることで、レコードを更新したりSELECTするために他の共有ロックが行われるのを防ぎます。Alternatively, you may use the lockForUpdate method. A "for update" lock prevents the rows from being modified or from being selected with another shared lock:

DB::table('users')->where('votes', '>', 100)->lockForUpdate()->get();

デバッグDebugging

クエリを組み立てる時に、クエリの結合とSQLをダンプするために、dddumpメソッドが使用できます。ddメソッドはデバッグ情報を出力し、リクエストの実行を中断します。dumpメソッドはデバッグ情報を出力しますが、リクエストは継続して実行されます。You may use the dd or dump methods while building a query to dump the query bindings and SQL. The dd method will display the debug information and then stop executing the request. The dump method will display the debug information but allow the request to keep executing:

DB::table('users')->where('votes', '>', 100)->dd();

DB::table('users')->where('votes', '>', 100)->dump();

章選択

設定

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

ヘッダー項目移動

キーボード操作