I am wrestling around a bit with CakePHP HABTM relationships, and I've gotten stuck trying to do a seemingly simple task. I have many Camps and many NewsItems. Each NewsItem could be relevant to any of the camps, so when a user creates a NewsItem, they check which Camps the item is for. That's the idea.
So...
I would like to incorporate some camp filtering into my NewsItems views. In other words, I would like to see all NewsItems relevant to Camp "A" and Camp "B".
Adding conditions to the "find" and "paginate" functions work like a charm.
However...
If a NewsItem belongs to multiple Camps, it appears multiple times in the list. So when I tell find to give me all NewsItems that belong to Camp "A" and Camp "B", a NewsItem that belongs to Camp "A" and Camp "B" will appear twice.
The debug query looks like this:
SELECT
NewsItem
.id
,NewsItem
.user_id
,NewsItem
.heading
,NewsItem
.body
,NewsItem
.modified
,User
.first_name
FROMnews_items
ASNewsItem
LEFT JOINusers
ASUser
ON (NewsItem
.user_id
=User
.id
) LEFT JOINcamps_news_items
ASCampsNewsItem
ON (CampsNewsItem
.news_item_id
=NewsItem
.id
) WHERECampsNewsItem
.camp_id
IN (1, 5) ORDER BYNewsItem
.modified
desc LIMIT 10SELECT
Camp
.id
,Camp
.name
,Camp
.created
,Camp
.modified
,CampsNewsItem
.camp_id
,CampsNewsItem
.news_item_id
FROMcamps
ASCamp
JOINcamps_news_items
ASCampsNewsItem
ON (CampsNewsItem
.news_item_id
IN (6, 6, 7, 8) ANDCampsNewsItem
.camp_id
=Camp
.id
) WHERE 1 = 1
The php code looks like this:
$camp_ids = array(1, 3, 6, 10);
$conditions = array('CampsNewsItem.camp_id' => $camp_ids);
$params['conditions'] = $conditions;
$this->NewsItem->bindModel(array('hasOne' => array('CampsNewsItem')));
$news_items = $this->NewsItem->find('all', $params);
Thanks for any insight!