Search code examples
phpcakephpmany-to-manyhas-and-belongs-to-many

CakePHP select many to many (HABTM) records


after create a many to many (HABTM) relationship between 2 classes (as code bellow) I was expecting to see results including the related records but for some reason this is not happening.

Models

App::uses('AppModel', 'Model');
class NewsCategory extends AppModel{
  public $hasAndBelongsToMany = array('News');
}

App::uses('AppModel', 'Model');
class News extends AppModel{
  public $hasAndBelongsToMany = array('NewsCategory');
}

I created a table called "news_news_categories" with both tables id.

Controller

this->data = $this->News->find('first', array('conditions' => array('News.id' => $id)));

The result from code above doesn't include the related NewsCategory records.

After spend hours trying to make this happen, I couldn't get this done.

What I'm missing here?

Thank you all in advance!


Update

When I dump the SQL code used by CakePHP using

echo $this->element('sql_dump');

the results didn't show any query (or joining) for this relationship. CakePHP is simply ignoring the $hasAndBelongsToMany config.


Solution

  • Finally found the solution. Basically I did the following steps:

    1. Created a new php file to represent the relationship model (for some reason I had understood that CakePHP would do it automagic behind the scenes)

      App::uses('AppModel', 'Model');
      class NewsNewsCategory extends AppModel{
        var $belongsTo = array('News', 'NewsCategory');
      }
      
    2. Changed my query code to bellow:

      this->data = $this->News->find('first', array('conditions' => array('News.id' => $id)), 'contain' => array('NewsCategory'));
      
    3. Finally I was expecting to get the results inside the same array like:

      $this->data['News']['NewsCategories'] //or anything like that
      

    But I discovered the related NewsCategory records was available on another var:

    $this->data['NewsCategory']
    

    (and not nested in the News result array, as I first supposed)

    Thank you all. I hope this helps other people in the future.