CakePHPからPostgreSQLの正規表現を利用する、きっと冴えたやり方
実際のとこ、かなり泥臭いやり方なので全然冴えてはいないところですが……。
あるマスタのテーブルドには、番号体系の正規表現を保存した列がある。
ユーザは、入力したコードを番号体系の正規表現でパターンマッチングして、マスタから特定のレコードを検索する。
こんな感じのテーブル
カラム | 型 | 修飾語 --------+--------------+---------- id | character(6) | not null regexp | text | not null name | text | not null
正規表現のパターンマッチングでプライマリキーを検索してくるロジックは、たぶん↓みたいな実装がベターなんじゃないかなと思った。
public function regexExample($code) { $regexp = $this->getDataSource()->value($code, 'regexp'); $conditions = array("{$regexp} ~ {$this->alias}.regexp"); $query = array('fields' => "{$this->alias}.{$this->primaryKey}", 'conditions' => $conditions, 'recursive' => -1, 'callbacks' => false); $result = $this->find('first', $query); $code = ''; if ($result !== false) { $path = "{$this->alias}.{$this->primaryKey}"; $tmp = Set::extract($path, $result); if ($tmp !== null) { $code = (string)$tmp; } } return $code; }