68
64

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

LaravelのクエリビルダでSQL文を直接実行(select,insert,update,delete,その他)

Posted at

準備

config/app.phpaliasでファサードのエイリアスDBが登録されていることを確認

//config/app.php
'aliases' => [
    'DB' => Illuminate\Support\Facades\DB::class,
];

DBファサードを使うクラスでuseする

use DB;

select

DB::select("SELECT * FROM users");
DB::selectOne("SELECT * FROM users WHERE id = ?", [1]);

insert

DB::insert('insert into users (id, name) values (?, ?)', [1, 'Dayle']);

update

DB::update('update users set votes = 100 where name = ?', ['John']);

delete

DB::delete('delete from users WHERE id = ?' [1]);

その他

DB::statement('drop table users');
DB::statement('alter table users auto_increment = 1');

公式ドキュメントに掲載されているものだと、selectinsert等はあるが、そのほかのdropalter等は記載されていないので困っていた。
DB::statement()が使えるので色んなSQL文をLaravelから実行できる。

(参考)
http://recipes.laravel.jp/recipe/1036

68
64
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
68
64

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?