ひとり勉強ログ

ITエンジニアの勉強したことメモ

#12 データベース検索 -limit, offset-

今回は limit, offset を使用して必要なデータのみを抽出する方法を実装する。

limit - データ数を指定する

取り出すデータの数を指定する。引数を「10」にすれば10件のデータを取り出すことができる。

該当したデータが10件未満の場合は該当データ全件の抽出となる。 [sql] ->limit(抽出件数); [/sql]

使用例:10件指定する [sql] ->limit(10); [/sql]

offset - 何番目のデータを取り出すか指定

データを最初から取り出すのではなく、指定した位置から取り出すことができる。 引数に整数を渡すことで、その整数-1番目からのデータを取り出す。 1 番目が 0、2 番目が 1 という具合になる。 [sql] ->offset(整数 +1番目); [/sql]

使用例:5番目からデータを取り出す [sql] ->offset(5); [/sql]

では Heroes アプリケーションに追加実装する。

「power」の降順に、上位3番目から5件抽出する

「HeroesController」に記述していてた「find」アクションを変更する。

■場所 \htdocs\chococake\src\Controller ■ファイル名 HeroesController.php

[php highlight="59-67"] <?php namespace App\Controller;

use App\Controller\AppController;

/* * / class HeroesController extends AppController { public function add() { if ($this->request->is('post')) { $hero = $this->Heroes->newEntity(); $hero = $this->Heroes->patchEntity($hero, $this->request->data);

  if ($this-&gt;Heroes-&gt;save($hero)) {
    return $this-&gt;redirect(['action' =&gt; 'index']);
  }
}

}

public function index() { $this->set('heroes', $this->Heroes->find('all')); }

public function edit($id = null) { $hero = $this->Heroes->get($id); if ($this->request->is(['post', 'put'])) { $hero = $this->Heroes->patchEntity($hero, $this->request->data); if ($this->Heroes->save($hero)) { return $this->redirect(['action' => 'index']); } } else { $this->set('hero', $hero); } }

public function delete($id = null) { $hero = $this->Heroes->get($id); if ($this->request->is(['post', 'put'])) { if ($this->Heroes->delete($hero)) { return $this->redirect(['action' => 'index']); } } else { $this->set('hero', $hero); } }

public function find() { // $heroes = ; if ($this->request->is('post')) { $find = $this->request->data['find']; $heroes = $this->Heroes->find() // ->select(['id', 'name']) // ->where(function ($exp) { // return $exp->gte('power' , 100); // }) // 今回変更部分:findアクション ->order(['power' => 'Desc']) ->offset(2) ->limit(5) ->where(['name like ' => '%' . $find . '%']); } else { $heroes = ; } $this->set('heroes', $heroes); }

} [/php]

解説

[php] ->offset(2) [/php] offset メソッドで最初の 3 番目から抽出。

[php] ->limit(5) [/php] limit メソッドでデータを 5 件のみ抽出。

ビューテンプレートファイルは前々回のまま変更なし。

以下URLにアクセスし、「検索」ボタンを押下して以下画像のように表示されればOK。
http://localhost/chococake/heroes/find

offset と limit を指定しなければ以下のように抽出される。

これが抽出条件の全データとなるため、3 番目から 5 件抽出できていることがわかる。