LoginSignup
8
12

More than 5 years have passed since last update.

[CakePHP3]ContainでSelectする場合の注意点

Posted at

ドキュメントをきちんと読めばわかる話しだが、少し手間取ったので念の為にメモっとく。

関連するテーブルのデータを取得したい場合は、containを利用すると思う。
その時に関連テーブルのカラムにデータ容量の大きいカラムがあるので、そのカラムは避けて取得したい。
そんな時は以下のような方法でselectするカラムを絞り込める。

例)

$this->テーブルモデル名->get($id, [
     contain => [
          テーブルA => function($q) {
               return $q->select([name])
          }
     ]
]);

ただし!上のやり方ではデータがあったとしても取得できない。

なぜか!?

それは外部キーの指定が必要だからだ。例えば外部キーがuser_idとしよう。
その場合、以下のようにuser_idを明示的に指定しなければならない。
例)

$this->テーブルモデル名->get($id, [
     contain => [
          テーブルA => function($q) {
               return $q->select([user_id, name])
          }
     ]
]);

以上がちょっとした注意点となる。

きちんとドキュメントを読めばわかる話(以下がそれについての記述)

When you limit the fields that are fetched from an association, you must ensure that the foreign key columns are selected. Failing to select foreign key fields will cause associated data to not be present in the final result.

8
12
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
8
12