问题
I am trying to find posts within a category that are associated with a category. Right now, I have this:
$this->set('posts', $this->Category->Post->find('all', array('conditions' => array('Category.uri' => $uri))));
But this doesn't seem to work. An error is showing this:
Warning (512): SQL Error: 1054: Unknown column 'Category.uri' in 'where clause' [CORE/cake/libs/model/datasources/dbo_source.php, line 684]
..<snipped>...
Query: SELECT `Post`.`id`, `Post`.`title`, `Post`.`uri`, `Post`.`body`, `Post`.`created`, `Post`.`modified` FROM `posts` AS `Post` WHERE `Category`.`uri` = 'holidays'.
I've read that when you have HABTM between models, you should be able to retrieve it like so. However, the SQL shown doesn't JOIN the categories table.
// Category Model
class Category extends AppModel {
var $name = 'Category';
var $hasAndBelongsToMany = array(
'Post' => array(
'className' => 'Post'
)
);
}
// Post Model
class Post extends AppModel {
var $name = 'Post';
var $hasAndBelongsToMany = array(
'Category' => array(
'className' => 'Category'
)
);
}
回答1:
I've read that when you have HABTM between models, you should be able to retrieve it like so.
I don't know where you read this, but your source is wrong. Cake's documentation of HABTM associations deals with a scenario almost identical to yours, and the steps necessary to achieve the results you're after.
My answer to another question about HABTM may be informative for understanding how Cake's ORM works under the covers.
回答2:
It seems that this worked. Is there a more efficient way to do this?
$options['joins'] = array(
array('table' => 'categories_posts',
'alias' => 'CategoriesPosts',
'type' => 'LEFT',
'conditions' => array(
'Category.id = CategoriesPosts.category_id'
)
),
array('table' => 'posts',
'alias' => 'Post',
'type' => 'LEFT',
'conditions' => array(
'CategoriesPosts.post_id = Post.id',
)
)
);
$options['conditions'] = array(
'Category.uri' => $uri
);
$options['fields'] = array(
'DISTINCT(Category.uri), Post.*, Category.*'
);
$this->set('posts', $this->Category->find('all', $options));
回答3:
This is the more efficient code:
$this->set('posts', $this->Category->find(
'first',
array(
'conditions' => array(
'Category.uri' => $uri
),
'contain' => array('Post')
)
));
来源:https://stackoverflow.com/questions/4268300/finding-records-via-conditions-in-habtm