illuminate/databaseを使用したデータベース操作

素で「illuminate/database」を使用したデータベース操作のまとめ

github.com

前回の記事で以下のような感じにdbの接続設定を追加したので、それを使用します。

$container['db'] = function ($c) {
    $capsule = new \Illuminate\Database\Capsule\Manager;
    $capsule->addConnection($c['settings']['db']);
    $capsule->setAsGlobal();
    $capsule->bootEloquent();
    return $capsule;
};

素のSQLを使用したデータベース操作

# insert
$container['db']->getConnection()->insert('INSERT INTO user (name, created_at, updated_at) VALUES(:name, now(), now())',['name' => 'test1']);

# update
$container['db']->getConnection()->update('UPDATE user SET name = :name, updated_at = now() WHERE id = 3',['name' => 'test10']);

# delete
$container['db']->getConnection()->delete('DELETE FROM user WHERE name = :name',['name' => 'test4']);

# select
$container['db']->getConnection()->select('SELECT * FROM user WHERE id > :id', ['id' => 3]);

# 戻り値が返ってこないようなデータベース操作のSQL
$container['db']->getConnection()->statement('DROP TABLE user');

# トランザクション
$container['db']->getConnection()->beginTransaction();
try {
    $container['db']->getConnection()->insert('INSERT INTO user (name, created_at, updated_at) VALUES(:name, now(), now())',['name' => 'test']);
    $container['db']->getConnection()->commit();
} catch (\Exception $e) {
    $this->container['db']->getConnection()->rollback();
}

クエリビルダーを使用したデータベースの操作

# insert
$this->container['db']->table('user')->insert(['id' => 8, 'name' => 'test8', 'created_at' =>  \Carbon\Carbon::now(), 'updated_at' =>  \Carbon\Carbon::now()]);

# update
$this->container['db']->table('user')->where('id', '=', 2)->update(['name' => 'test12']);

# delete
$this->container['db']->table('user')->where('id', '=', 7)->delete();

# select
$users = $this->container['db']->table('user')->where('id', '>', 1)->get();


その他、クエリービルダーの記述法

laravel.com