CakePHP Note (v1.3) > モデル > データの取得
データの取得
レコードの検索はfindメソッドを使用します。findメソッドでは検索のタイプを指定し、必要に応じてオプションを指定します。
- find(string $type, array $options)
検索のタイプ
検索のタイプは以下のいずれかを指定できます。
- all(全てのレコード)
- first(最初のレコード)
- count(レコード数)
- list(リスト表示用の配列を取得)
- neighbors(前後のレコード)
- threaded(親子関係のレコード、ツリー状にネストされた配列を取得できる)
オプションの指定
オプションとして以下の項目を指定できます。
- 検索条件(conditions)
- ソート順(order)
- 取得するフィールド(fields)
- 結合(joins)
- グループ化(group)
- 取得上限(limit)
- アソシエーションの指定(recursive)
- コールバック(callbacks)
- 取得する関連モデル(contain/Containableビヘイビア使用時)
検索条件
その他のオプション
グループ化(Group By)
$option['group'] = array('Post.id');
ソート順の指定
検索条件と同様に、テキストまたは配列で指定します。
$options['order'] = array("Post.created" => "ASC", "Post.title" => "DESC"); $this->Post->find('all',$option);
フィールドの指定
取得するフィールドを限定したい時は、配列で指定します。
$options['fields'] = array('Post.created','Post.title'); $this->Post->find('all',$option);
アソシエーションの指定
同時にどのレベルまで関連レコードを取得するか指定します。
$options['recursive'] = 2; $this->Post->find('all',$option);
結合するテーブル
結合したいテーブルを明示的に指定します。typeにはSQLでJOINの前に記述するキーワード(INNER,LEFT等)を指定します。 $options['joins'][]=array( 'type' => 'LEFT', 'alias' => 'User', 'table' => 'users', 'conditions' => 'User.id = Post.user_id');
findByフィールド名
findById, findByTitleなどfindByフィールド名というメソッドで検索する事も出来ます。
$this->Post->findById(7);