findで実行されるSQLは、以下のようなものを想定してしますか?
SQL
1select DISTINCT id from post_tag
2where tag_id = 'a' or tag_id = 'b' or tag_id = 'c';
であれば、以下のように'fields'にDISTINCT 「出力したいカラム」を設定すればよいと思います
PHP
1$tags = array("a", "b", "c");
2
3$result = $this->PostsTag->find('list', array(
4 'conditions' => array(
5 'PostsTag.tag_id' => $tags
6 ),
7 'fields' => array('DISTINCT PostsTag.id')
8 )
9);
追記:
取得したいことが、おおよそわかりました
tagsに含まれているすべてのtagを持つpost_idを取得するのですね?
例)tags=(a,b,c) post_id=1 tags=(a,b) post_id=2
この場合のSQLは、以下のようなものになると思います
SQL
1SELECT
2 posts_tag.post_id
3FROM
4 irie.posts_tag
5 inner join
6 (select post_id from irie.posts_tag
7 where tag_id in ($tags)
8 group by post_id) temp_post_tag
9 on
10 temp_post_tag.post_id = posts_tag.post_id
11group by
12 posts_tag.post_id
13having
14 count(posts_tag.post_id) = $tagsの要素数
このSQLはサブクエリを使用しているので、CakePHPのコードでは
以下のように実装できると思います
PHP
1 $tags = array("a", "b", "c");
2 $cnt = count($tags);
3
4 // サブクエリ設定
5 $dbo = $this->PostsTag->getDataSource();
6 $subQuery = $dbo->buildStatement(
7 array(
8 'table' => $dbo->fullTableName($this->PostsTag),
9 'alias' => 'wkPostsTag',
10 'fields' => array(
11 'post_id'
12 ),
13 'conditions' => array('wkPostsTag.tag_id' => $tags),
14 'limit' => null,
15 'joins' => array(),
16 'order' => null,
17 'group' => array('wkPostsTag.post_id')
18 ),
19 $this->PostsTag
20 );
21 // 本体設定
22 $options = array(
23 'joins' => array(
24 array(
25 'table' => "({$subQuery})",
26 'alias' => 'wkPostsTag',
27 'type' => 'INNER',
28 'conditions' => 'wkPostsTag.post_id = PostsTag.post_id'
29 )
30 ),
31 'fields' => array('PostsTag.post_id'),
32 'group' => array("PostsTag.post_id HAVING count(PostsTag.post_id) = ".$cnt)
33 );
34 // 検索の実行
35 $data = $this->PostsTag->find('list',$options);
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2015/10/07 15:08