Skip to content

Instantly share code, notes, and snippets.

@nazo
Last active August 29, 2015 14:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nazo/de02ea6c4abf470b8b4c to your computer and use it in GitHub Desktop.
Save nazo/de02ea6c4abf470b8b4c to your computer and use it in GitHub Desktop.
[php][laravel5]DB周り

基本的な使い方

    $results = \DB::select('select * from articles where id = ?', [2]);

Query Builderの説明を読んだほうが早い。通常はEloquent使うと思うので使わないと思う。特殊なSQLを発行したい時に使おう。

Eloquent ORM

use Illuminate\Database\Eloquent\Model;
class User extends Model
{
    protected $table = ‘users'
}

こんなModelをどこかに書いて(どこでもいい)

$users = User::where(‘group_id’, ‘=‘, 1)->get();

こんな感じで呼び出せる。詳細はEloquent ORMの説明を読もう。 何故か行ロックは実装されていないので、

public static function lock($id, $columns = array('*'))
{
    $instance = new static;

    if (is_array($id) && empty($id)) return $instance->newCollection();

    return $instance->newQuery()->lockForUpdate()->find($id, $columns);
}

こんなのを用意しておくと便利。

トランザクション

DB::beginTransaction();

// 処理

DB::commit();

DB::rollback();
||<
で行けるが、
>|php|
DB::transaction(function() {
    // 処理
});

でも可能。この場合、例外で終了するとrollbackするようになる。

複数接続

DB::connection(‘other_connection_name’)->select(...);

のような感じで可能。DBは(デフォルトでは)\Illuminate\Database\DatabaseManagerのFacadeなので、そのままstaticアクセスするとデフォルトの\Illuminate\Database\Connectionになるし(__call()でたらい回ししてる)、DB:connection()でインスタンスを返してそれを操作することもできる。

** デフォルト接続を途中で変える

DB::setDefaultConnection(‘new_connection_name’);

ORMとうまく組み合わせると、複数の同一構造のDBを操作したりできる、かもしれない。

Modelの接続先を変える

class Hoge extends Model
{
    protected $connection = ‘new_connection_name’;
}

ちなみにmigrationでも同じように$connectionで接続先を指定できる。複数DBを扱う時でも安心。

JOIN

hasManyとかはデータ取得には使えるけどJOINクエリの構築には(あまり)使えない。 素直にJOINを書こう。 ちなみにJOINする時はselect(‘table_name.*’)を書かないと、デフォルトでSELECT * FROM〜するので、同名カラムが他テーブルに含まれてると壊れる。

例えば、SELECT users.* FROM users INNER JOIN comments AS c ON users.id = c.user_id WHERE c.created > 10のようなクエリは、

Users::select('users.*')->join('comments as c', 'users.id', '=', 'c.user_id')->where('c.created', '>', 10)->get();

のように書く。 ON句をもっと詳しく書きたい、例えば複数条件や定数、NOT NULL等をONに入れたい場合は、JOINの第二引数に無名関数を入れる。

Users::select('users.*')->join('comments as c', function($join) {
   $join->on('c.user_id', '=', 'users.id');
   $join->where('c.blog_id', '=', 3);
})->where('c.created', '>', 10)->get();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment