LoginSignup
27
14

More than 5 years have passed since last update.

CakePHP3のORMにおけるget()とfind()の違い

Last updated at Posted at 2016-09-25

開発中にハマったのでメモしておきます。

get() で指定した id に該当するデータが存在しなかった場合は RecordNotFoundException 例外が発生する。

public function view($god_id = null)
{
    /* 指定した id に該当するデータが存在しなかった場合はエラーになる */
    $god = $this->Gods->get($god_id);

    $this->set('god', $god);
}

それに対して、クエリビルダのfind()に続くwhere()で id を指定した場合は、1件もデータを取得できなくてもエラーは発生せず後続の処理を行う。

public function view($god_id = null)
{
    /* 指定した id に該当するデータが存在しなかった場合でもエラーにはならない */
    $god = $this->Gods->find()->where(["god_id = " => $god_id]);

    $this->set('god', $god);
}

結論
絶対に1件以上のデータを取得できる保証がある時にはget()を使ったほうが簡潔に書ける。
しかし、1件もデータを取得できない可能性がある場合はクエリビルダのfind()に続くwhere()で id を指定したほうが無難である。

27
14
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
27
14