LoginSignup
1
2

More than 1 year has passed since last update.

【CakePHP3】指定したキーの値を配列で取得する

Posted at

普段、Laravelを主に使っていたのですが、CakePHPを業務で使用する機会があったので、備忘録として残します。

テーブルの$item_idで検索を立てて、該当するレコードのnameを取得したいとします。

$results = $this->DataBases
     ->find()
     ->where([
         'item_id' => $item_id,
     ]);
foreach ($results as $result) {
     $arrayData[] = $result->name;
}
dd($arrayData);
//結果:arrayData[名前1, 名前2, 名前3]

とりあえずこれでもうまくいったのですが、せっかくなのでCakePHPを使い倒したい!
ということでCakePHPの場合、下記の方法でも取得することができます。

use Cake\Collection\Collection;
.
.
.
$results = $this->DataBases
     ->find()
     ->where([
         'item_id' => $item_id,
     ]);
$arrayData = $collection->extract('site_id')->toList();
dd($arrayData);

LaravelでいうところのCollectionのpluckメソッドの使い方に近いかもしれません。
CakePHPのcollectionクラスも覚えれば楽しめそうですね^^

1
2
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
1
2