CakePHPのSearch Pluginを使いhasManyの検索を作成しています。フォームでチェックボッックスで複数の値を選択した場合に検索する方法を教えてください。
[開発環境]
CakePHP 2.x
(データベース)
posts(id,title)
posts_tags(id,post_id,tag_id)
tags(id,name)・・・今回は使いません(上記の2つのテーブルを利用)
Post.php(モデル)
class Post extends AppModel {
public $actsAs = array('Search.Searchable');
public $filterArgs = array(
array('name' => 'id', 'type' => 'value'),
array('name' => 'title', 'type' => 'like'),
array('name' => 'PostsTag.tag_id', 'type' => 'like'),
);
public $presetVars = array(
array('field' => 'id', 'type' => 'value'),
array('field' => 'title', 'type' => 'value'),
array('field' => 'tag_id', 'type' => 'value')
);
var $hasMany = array(
'PostsTag' => array(
'className' => 'PostsTags',
'foreignKey' => 'post_id',
'conditions' => '',
'fields' => '',
'order' => ''
));
PostsController.php(コントローラー)
class PostsController extends AppController {
public $name = 'Posts';
var $uses = array ('Post','PostsTag');
public $components = array ('Search.Prg');
function search(){
$this->presetVars = $this->Post->presetVars;
$this->Prg->commonProcess();
$req = $this->passedArgs;
$this->paginate = array(
'conditions' => $this->Post->parseCriteria($req),
'limit' => 20,
'paramType' => 'querystring',
'recursive' => 2,
);
$this->set('record', $this->paginate());
$tags = $this->Tag->find ( 'list');
$this->set(compact('tags'));
}
この状態でpr($this->paginate());を行ってみると、下記のような形でデータが表示されます。
Array
(
[0] => Array
(
[Post] => Array
(
[id] => 1
[title] => 今日は晴れです
[body] =>
)
[PostsTag] => Array ( [0] => Array ( [id] => 1 [post_id] => 1 [tag_id] => 1 ) [1] => Array ( [id] => 7 [post_id] => 1 [tag_id] => 3 ) ) ) [1] => Array ( [Post] => Array ( [id] => 2 [title] => 今日は雨です [body] => ) [PostsTag] => Array ( [0] => Array ( [id] => 2 [post_id] => 2 [tag_id] => 2 ) [1] => Array ( [id] => 8 [post_id] => 2 [tag_id] => 3 ) ) )
次にviewのフォームでtitleとpost_idという項目を作ります。
search.ctp(ビュー)
echo $this->Form->create ( 'Post', array (
'type' => 'post',
'controller' => 'posts',
'action' => 'search',
) );
echo $this->Form->input ( 'title', array ('label'=>'','class'=>'','cols'=>'','rows'=>'','value'=>''));
echo $this->Form->input( 'tag_id', array(
'type' => 'select',
'multiple'=>'checkbox',
'options' => $tags,
));
echo $this->Form->end('送信');
POSTした状態でコントローラーでpr($req);を実行してみると
Array
(
[title] => 晴れ
[tag_id] => Array
(
[0] => 3
[1] => 2
)
)
という形でデータが取得できます。
PostsTagのtag_idが2と3のどちらかが含まれるPostのidを取得するにはどのようにすれば良いのでしょうか?
hasManyはJOINではなく、複数回クエリを投げる仕組みということはわかりました。
モデルの array('name' => 'PostsTag.tag_id', 'type' => 'like'), の部分でクエリを作って設定するか、コントローラの$reqに直接記載するなどの方法が考えられますが、どのようにプログラムを書いたらいかがわかりません。
ご回答よろしくお願いします。
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。