I have a problem, I need to retrieve a single field from a single record, without the associated models, while using conditions that uses the associated models?
开发者_StackOverflowExample:
Categories {name, id}
Keywords {name, id}
Articles {title, text, id, keyword_id, category_id}
I want to retrieve the first Articles.id
when Article.category_id=3
etc.
Using Model->field('model.field',array(conditions))
is working as long the conditions are not using the outer models. ($this->Model->recursive=4
isn't working).
Using Model->find('first', array(conditions))
works fine, except the fact that I get also the associated data that I don't need and don't want, limiting the recursion results with disabling the ability to use the associated models comparison..
any advice?
edit
my problem, except from being poor debugger :-) was solved by limiting the recursion while using the model->read
method.
however, the long term is, probably, using the containable behavior.
The find() method takes a fields
argument as one of its options. You can also set the recursive
argument to ensure you are getting the appropriate level of relationships.
Based on your OP, the following will retrieve what you want without joining any relationships.
$this->Article->find('first', array('recursive' => -1, 'fields' => array('Article.id'), 'conditions' => array('Article.category_id' => 3)));
If your requirements are stronger than the above, you can look at binding models or Containable Behavior. But from what you described, the above is the appropriate solution. These would be overkill IMO.
I would use Model->find()
with the containable behavior to limit what associations are loaded and the field argument to limit the results only to the desired field.
精彩评论