1

I'm writing a simple Blog application. I am dealing with two models, BlogPost and BlogCategory.

They both have a HABTM relationship to each other using a separate table.

I have written a function in the BlogPost model to load all the posts from a certain category, but it keeps producing a database error.

public function getRecentFromCategory($category, $offset, $limit){
     return $this->find('all', array(
         'order' => 'BlogPost.date desc',
         'offset' => $offset,
         'limit' => $limit,
         'conditions' => array('BlogCategory.id' => $category)
     ));
 }

Why can't I make a conditional based on the associated categories?

Leah Sapan
  • 3,621
  • 7
  • 33
  • 57
  • It shows the query but it clearly isn't actually linking to BlogCategory in the query. It just suddenly has a WHERE BlogCategory.id=etc, but it never sets up the relationship. – Leah Sapan Sep 04 '13 at 22:35
  • 1
    http://stackoverflow.com/a/328876 | http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#joining-tables – ndm Sep 04 '13 at 22:41
  • I just feel like something as simple as searching within a related model should be simpler than that. Is that really the only way? – Leah Sapan Sep 04 '13 at 22:59
  • AFAIK this is unfortunately the only way if you want to use the Cake syntax. – ndm Sep 04 '13 at 23:48

1 Answers1

0

You need to set up a belongsTo relationship between your models, meaning your BlogPosts can belong to a BlogCategory.

Assuming your BlogPost has a 'blog_category_id' field, in your BlogPost model:

public $belongsTo = array(
    'BlogCategory' => array(
        'className' => 'BlogCategory',
        'foreignKey' => 'blog_category_id'
    )
);

Then your find should be able to filter based on category in the way you want.

Derek
  • 4,575
  • 3
  • 22
  • 36
  • In a `HABTM` relationship the foreign keys are in the join table, so creating a `belongsTo` relationship is not possible. – ndm Sep 05 '13 at 11:34
  • My bad, I didn't see the HABTM part of his post. Same thing though, you would use a syntax such as this (as described on the book link you posted in the OP comments), and set up your join table. – Derek Sep 05 '13 at 13:59