views:

116

answers:

1

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 FROM news_items AS NewsItem LEFT JOIN users AS User ON (NewsItem.user_id = User.id) LEFT JOIN camps_news_items AS CampsNewsItem ON (CampsNewsItem.news_item_id = NewsItem.id) WHERE CampsNewsItem.camp_id IN (1, 5) ORDER BY NewsItem.modified desc LIMIT 10

SELECT Camp.id, Camp.name, Camp.created, Camp.modified, CampsNewsItem.camp_id, CampsNewsItem.news_item_id FROM camps AS Camp JOIN camps_news_items AS CampsNewsItem ON (CampsNewsItem.news_item_id IN (6, 6, 7, 8) AND CampsNewsItem.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!

+1  A: 

Try this:

$params['group'] = array('NewsItem.id');
deceze
Perfect! Thanks so much!
just_wes
Any idea how to get that to work properly with the paginate helper?
just_wes