LoginSignup
23
21

More than 5 years have passed since last update.

EloquentでPrimary KeyをComposite keyで指定した場合の問題

Last updated at Posted at 2014-07-06

LaravelのOR MapperであるところのEloquentでは以下のようにPrimary Keyを指定できる。

protected $primaryKey = ['foo_id', 'bar'];

ところが、SeederとかでModel::createとかでデータを突っ込もうとすると以下の様なエラーに出会うことがある。

PDO::lastInsertId() expects parameter 1 to be string, array given

Laravel seed table with composite primary keyによれば、"Eloquent does not support composite keys"だそうで、以下のようにやればとりあえずエラーは回避できる。

$data = [
          [
                'foo_id' =>1,
                'bar'    =>'abc',
          ],
          [
                'foo_id' =>2,
                'bar'    =>'def',
          ]
        ];
DB::table('tablename')->insert($data);

ただしこれだとテーブル名をかなかくちゃいけないので嫌な感じなので、モデルクラスから名前を取りたい。モデルから名前を取る方法として"Can't get Eloquent model's table name without an instance of the model"を読むと、getTableというメソッドがあるが、インスタンスメソッドなのでインスタンスを生成しないと取得できない。こうすれば取れるけどイケてない感じがあって

$table = with(new Model)->getTable();

以下の様な方法が書かれている。クラスメソッドつくる。結局は一旦オブジェクト生成してるのであんまり変わらないんだけど、とりあえず。

class BaseModel extends Eloquent {
    public static function getTableName()
    {
        return with(new static)->getTable();
    }
}

class User extends BaseModel {
}

User::getTableName();
23
21
1

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
23
21