CakePHP Filtering associated model by array

1k Views Asked by At

I have models: Project=>Keyword

using HMBTM relationship (set in both models).

The keywords table acts as a Tree, ie. the keywords have hierarchical relationship amongst themselves.

I am using containable behavior.

A user selects a keyword.

I want the returned records (Projects) to be limited by the selected keyword, OR any of that keyword's children. I am trying to reuse my index action.. if no keyword is selected then render the standard index view, if keyword is selected, then find all child keywords and then filter returned projects to those with any of the keyword ids.

I have tried creating an array of children (and original) keyword ids, but I can't work out how to get that array to become the filtering in my find action.

I have tried using :

$this->Project->find('all',
    array(
        'contain' => array('Keyword.id'=>array($childkeywords))     
    )
);

where $childkeywords is an array of the relevant ids, created using array_push. But that does not use key-value pairs, just int values for each id. So I think it is not structured properly.

I feel I want to do something quite easy, but sense I am getting further away from the solution. Is there not a standard way to limit the records to a collection of ids of an associated model?

Cheers

With help from Paulo, I now have:

$this->Project->find('all', array(
                                    'fields' => array('id','title','country', 'project_ref'),
                                    'type' => array('inner'),
                                    'contain' => array('Keyword' => array(
                                                                'conditions' => array('Keyword.id' => $childkeywords)                                               
                                                                            )
                                                    )
                                            )
                                )

But the use of type inner is not changing the results..

2

There are 2 best solutions below

4
On

You should have something like this:

$this->Project->find('all', array(
    'contain' => array('Keyword' => array(
                'conditions' => array('Keyword.id' => $childkeywords)
            )
    )
));
2
On

Try something like this:

$this->Project->Keyword->find('all', array(
    'conditions' => array(
        'Keyword.id' => array(1, 2, 3, 4)
    )
));

You do not need to use Containable in this case.

Or you can try TreeBehavior.