52
39

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【CakePHP】findBy/findAllBy(マジックメソッド)

Last updated at Posted at 2014-03-13

使い方

Byのあとをカラム名と見なして検索する。
以下は「where User.id=123」と同じ。

findBy
$this->User->findById(123); 
```

````php:findAllBy
$this->User->findAllById(123); 
```

**findByは単一レコード取得のfind('first')と同じ
findAllByは複数レコード取得のfind('all')と同じ**

# 戻り値
**findByはfind('first')と同じ**
**findAllByはfind('all')と同じ**

```php:findByの戻り値
array(
  'User' => array(
    'id' => '123',
    'name' => 'suzuki',
  )
)
```

```php:findAllByの戻り値
array(
  0=>array(
    'User' => array(
      'id' => '123',
      'name' => 'suzuki',
    )
  )
)
```

# 複数カラムを検索対象にすることも可能
複数カラムをOrやAndでつなぐ

```php
//「User.email = 'jhon' OR User.username = 'jhon'」と同じ。
$this->User->findByEmailOrUsername('jhon');	

//「User.username = 'jhon' AND User.password = '123'」と同じ。
$this->User->findByUsernameAndPassword('jhon', '123');	
```

# 取得フィールド、ソートなどの指定も可能

```php
$this->findByカラム名('カラム条件',fields,order,recursive);
```

パラメータが連想配列ではないので使わないところはnullで渡す

```php
$this->findByカラム名('カラム条件',null,array('created'));
```



参考[findByカラム名のオプション](http://pnome.blog88.fc2.com/blog-entry-90.html)
52
39
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
52
39

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?