環境
PHP 7.3.24
Laravel 6.20.30
MAMP
クエリビルダとは
・SQLに近い構文をPHPのメソッドとして使い、DBを操作するもの
・メソッドチェーンで記述可能
・ DB::table(テーブル名)->SQL
という書き方をする
使用例
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;
class ProductController extends Controller
{
public function index() {
// products テーブルのproduct_nameカラムのデータを取得
DB::table('products')
->select('id', 'product_name')
->get()
->dd();
}
}
dd()
の実行結果は以下の通りです。
DBのid
とproduct_name
の値を取得できていることがわかります。
Illuminate\Support\Collection {#384 ▼
#items: array:9 [▼
0 => {#385 ▼
+"id": 1
+"product_name": "ノート"
}
1 => {#389 ▼
+"id": 2
+"product_name": "タブレット"
}
2 => {#390 ▼
+"id": 3
+"product_name": "タピオカ"
}
3 => {#391 ▼
+"id": 4
+"product_name": "カーテン"
}
4 => {#392 ▼
+"id": 5
+"product_name": "ピアノ"
}
5 => {#393 ▼
+"id": 6
+"product_name": "うまい棒"
}
6 => {#394 ▼
+"id": 7
+"product_name": "炊飯器"
}
7 => {#395 ▼
+"id": 8
+"product_name": "りんご"
}
8 => {#396 ▼
+"id": 9
+"product_name": "switch"
}
]
}