Hello.
I'm creating a search engine for a blog and I've got a problem with
selecting posts based on a given, several tags.
I have following models:
- Post (posts)
- Tag (tags)
- PostsTag (posts_tags)
In Post model there is a hasAndBelongsToMany relationship with Tag model
defined.
Let's say I have following posts and tags assigned to them:
- "Raspberry icecream" - with "icecream" tag assigned
- "Pineapple icecream" - with "icecream" and "pineapple" tags assigned
- "Pineapple pie" - with "pineapple" and "pie" tags assigned
What I'm trying to do is select posts that match not only one tag, but all
the tags that are specified in a search phrase.
Let's say that I've entered to the search engine following search phrase:
"pineapple icecream" .
Now, what I want to achieve is to posts that have "pineapple" tag assigned
to them and also have "icecream" tag assigned.
So in search results there is only "Pineapple icecream" displayed, because
it is assigned to both search conditions words - pineapple and icecream.
How can I do this?
I tried like that:
$tags=$this->Tag->find('all',array('conditions'=>$cond,'fields'=>array('id')));
//here I get all the tags that match every word in search conditions
if($tags) {
foreach($tags as $t) {
$tags_ids[]=$t['Tag']['id'];
}
$posts_tags=$this->PostsTag->find('all',array('conditions'=>array('tag_id'=>$tags_ids),'fields'=>array('post_id')));
if($posts_tags) {
foreach($posts_tags as $pt) {
$posts_ids[]=$pt['PostsTag']['post_id'];
}
}
}
and then I do the search for posts based on the $posts_ids condition.
But with this solution, I get in search results all the posts, which have
either "icecream" tag or "pineapple" tag. Which does not suit my needs.
Any help will be greatly appreciated.
--
Like Us on FaceBook https://www.facebook.com/CakePHP
Find us on Twitter http://twitter.com/CakePHP
---
You received this message because you are subscribed to the Google Groups
"CakePHP" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
Visit this group at http://groups.google.com/group/cake-php?hl=en.