CakePHPでOR検索(ANDは難しかった)
Posted on | 2009/10/23 20:21:21
結局、暇を見つけては毎日触っておる、ET withwithの開発ですが、今日は「CakePHPに簡単な検索機能を実装する」でやった検索を複数語に対応させる修正をしました。下記のページが大変参考になりました。
フォームからand,or検索を実装したSQLを生成する – PHPに惚れました。
ただ検索語が複数語になるだけではなくて、ET withwithでは3つのフィールドを検索対象にしなければならなかったので、上記の方法がピッタリでした。ただ、表題のとおり、AND検索が、上のロジックのままではできず(自分が意図しているAND検索とは違う)、とりあえず、OR検索のみをデフォルトで対応することにしました。
contents_controller.php
function view_search() {
function addsl($comment) {
$comment = mysql_real_escape_string($comment);
$comment = preg_replace("/%/","\%",$comment);
$comment = preg_replace("/_/","\_",$comment);
$comment = htmlspecialchars($comment, ENT_QUOTES);
return $comment;
}
$key = $this->data['key'];
$like = ”;
if (!empty($key)) {
$key = trim($key);
if(preg_match("/[ | ]+/", $key,$num)){
$key = mb_convert_kana($key, "s");
$keywords=preg_replace(‘/\s+/’, ‘ ‘, $key);
$keywords = explode(" ",$keywords);
foreach($keywords as $cli){
if($cli != ""){
$cliwd[] = "Client.client LIKE ‘%".addsl($cli)."%’ ";
}
}
foreach($keywords as $tit){
if($tit != ""){
$titwd[] = "Content.title LIKE ‘%".addsl($tit)."%’ ";
}
}
foreach($keywords as $con){
if($con != ""){
$conwd[] = "Content.content LIKE ‘%".addsl($con)."%’ ";
}
}
} else {
$keywords = $key;
}
}
if (!empty($titwd) || !empty($conwd) || !empty($conwd)) {
$like .= implode(" or ",$cliwd)." or ";
$like .= implode(" or ",$titwd)." or ";
$like .= implode(" or ",$conwd);
$where = "(".$like.")";
} else if (empty($key)) {
$where=$this->Session->read(‘where’);
} else {
$where = array("or" => array("Client.client LIKE" => "%".$key."%", "Content.title LIKE" => "%".$key."%", "Content.content LIKE" => "%".$key."%"));
}
$this->Session->write(‘where’,$where);
$this->Content->order = "date DESC";
if (!empty($where)) {
$this->set(‘contents’, $this->paginate(‘Content’,$where));
} elseif (empty($where)) {
$this->set(‘contents’, $this->paginate());
}
$this->render(‘index’);
}
最後に躓いたのが、mb_convert_kanaが機能しなかったこと。散々悩んで、ネットでは改行コードを指定してやる解決法なども乗っていたのですが、よくよく調べると、単純にcontents_controller.php自体を保存した時の改行コードがUTF-8になっていなかった!で全角スペースが全角スペースとして認識されず、全角スペースを半角スペースに変換する処理が、機能していなかったわけです。
実は後、ユーザの権限管理とユーザ認証などもやっぱりやりたいかなあなどと思っておるのですよね。。。触ってるとどんどんやりたいこと出て来ますね。。。


意外と知らない、「ヒトリシゴト」。案外、愉快で、楽しいです。気軽に読める、ビジネスエッセイ。

プランナー、加藤康祐のブログ、kosukekato.com : the idea espressoに掲載したコラム、2006/7/20「歴史は作られている」から2010/5/23「行為が流通するプラットフォームに新しい時代を感じる」を一冊の本にしました。

今話題のInstagramを使った写真集です!あなたもInstagramするきっかけになれば!68点の写真を収録。
- blog.daichisakota.com - ちょっと考えられないくらい美味かった「いわもと Q 」(麹町)
- TechCrunch Japanese - Instagramのファウンダのガールフレンドが自作のWebアプリをバレンタインデーギフトに
- TechCrunch Japanese - アメリカの世帯でケーブルTVの解約増加―視聴方法は大幅に多様化(Nielsen調べ)
- TechCrunch Japanese - Foursquare、モバイルアプリケーション版でも「探索」を充実して「地域検索エンジン」機能を強化
- TechCrunch Japanese - LinkedIn、ウォール街予測を上回る。Q4売上は105%増の1.677億ドル
- ハッカー集団、シマンテック「pcAnywhere」のソースコード公開 - CNET Japan
- blog.daichisakota.com - フリーランスになって一週間が経ちました












