开发者

CakePHP: hasMany model association not recursively fetching

I have the following association:

Site - hasMany - Sitekey Sitekey - belongsTo - Site

sites.id is primary key sitekeys.site_id is foreign key

in site model: var $hasMany = array('Sitekey');

the query: $this->find('all', array('conditions' => array('Sitekey.keyword_id' => $key), 'recursive' => 1));

fetching (find 'all') recursively with that association does not work. I have tried explicitly defining the class name, foreign key, etc...

As a last ditch effort, I simply tried changing the site model to: var $hasOne = array('Sitekey');

When I do the recursive find 'all' on this, it does the join and returns the data correctly. Any idea what I am doing wrong or tech开发者_如何学Goniques I can use to debug/fix the problem?

Thanks!


Have you tried providing the class and key when you specify hasMany (and belongsTo, for that matter)?

var $hasMany = array( 'Sitekey' => array(
  'className' => 'Site',
  'foreignKey' => 'site_id'
));

For me, this happens when the Inflector doesn't correctly singularize and pluralize your nouns. I've made it a practice to always check this first.

If this does work, then in theory you should look at why it's not recognizing it. Create another model Bar (or some other word that it knows), and give it the same associations as sitekey, and see if it works in your site. If so, again, it's most likely the inflector on Sitekey.


Could it be something simple like this? The $this keyword like you have used it (assuming we are in a controller) would be an instance of the controller, not the model. Therefore, your results would be based on the default model for the controller. Be sure your controller "uses" the model you are trying to query.

$results = $ModelName->find('all', array('conditions' => array('Sitekey.keyword_id' => $key), 'recursive' => 1));

I'd suggest looking into the containable behavior as well. You get more control than just using recursive.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜