tags:

views:

195

answers:

1

I am new to cakephp and I'm trying to accomplish something that should be relatively easy. I have 2 models projects & categories bind by HABTM relationship.

I am trying to perform the following query -> find all projects that belong to a category

$projects = $this->Project->find('all', array('conditions' => array('Category.slug' => $category)));

However when I'm doing so it generates an SQL error:

SQL Error: 1054: Unknown column 'Category.slug' in 'where clause' 

What am I doing wrong??

A: 

As far as I know,you can get what you want like this:

/*in Project Controller file*/

$categorys = $this->Project->Category->find('all', array('conditions' => array('Category.slug' => $category)));

And you will probably get somethin as follows if set you HABTM relationship correctly:

Array
(  
    [Category] => Array
    (
        [id] => xxx
        [name] => hello there
        ...
    )

    [Project] => Array
    (
        [0] => Array
            (
                [id] => 123
                [name] => Breakfast
            )
       [1] => Array
            (
                [id] => 124
                [name] => Dessert
            )
       [2] => Array
            (
                [id] => 125
                [name] => Heart Disease
            )
    )
)

It's what's you want,isn't it?See work with HABTM in cakephp in the cookbook.

SpawnCxy
If you see on my post I want to find all Projects under a Category.Your code seems to be dealing only with Categories and can only work (in to my knowledge) in the Categories Controller.I'm looking to retreive data in Projects Controller and in more detail all projects that fall into a specific category.For example my url would be like: sitename/projects/view/category-slug.
ion
@ion,you can just use "$this->Project->Category->find(...);" to do that,this is not a problem actually.See my update.
SpawnCxy
I tried doing that but it returns no projects. It finds the category but not the projects...I'm pretty sure I've set the HABTM relationships correctly. The mvc files have been generated by cake bake and the database is built the way cake suggests: projects, categories, projects_categoriesI don't understand what I'm missing here. I could paste the code from the files if you want (here or elsewhere).
ion
Man you were right!!!Thank you very much. It seems that I had foreign Key and association Foreign key mixed up while experimenting in the models file. :)
ion