如何在CakePHP中的包含模型中查找类别
发布时间:2020-12-13 17:05:12 所属栏目:PHP教程 来源:网络整理
导读:我最近有一个关于 Finding records via conditions in habtm的问题.现在,我可以搜索我搜索的类别中的帖子. 现在,我的问题是如何检索每个帖子的类别.有时,帖子在此查询中包含一个或多个类别: $this-set('posts',$this-Category-find( 'first',array( 'condit
我最近有一个关于
Finding records via conditions in habtm的问题.现在,我可以搜索我搜索的类别中的帖子.
现在,我的问题是如何检索每个帖子的类别.有时,帖子在此查询中包含一个或多个类别: $this->set('posts',$this->Category->find( 'first',array( 'conditions' => array( 'Category.uri' => $uri ),'contain' => array('Post') ) )); 我想象这样的事情: $this->set('posts','contain' => array('Post' => array( 'contain' => 'Category' )) ) )); 这是我的模型的样子. // Category Model class Category extends AppModel { var $name = 'Category'; var $hasAndBelongsToMany = array( 'Post' => array( 'className' => 'Post' ) ); var $actsAs = array('Containable'); } // Post Model class Post extends AppModel { var $name = 'Post'; var $hasAndBelongsToMany = array( 'Category' => array( 'className' => 'Category' ) ); var $actsAs = array('Containable'); var $virtualFields = array( 'date_posted' => 'DATE_SUB(Post.created,INTERVAL 7 DAY)' ); } 示例数据如下: categories id name 1 holidays 2 destinations posts id title 1 I am a post 2 I am another post categories_posts post_id category_id 1 1 2 2 2 1 我正在从假期中检索帖子. Array ( [Category] => Array ( [id] => 3 [name] => holidays [uri] => holidays [created] => 2010-11-25 20:43:03 [modified] => 2010-11-25 20:43:03 ) [Post] => Array ( [0] => Array ( [id] => 1 [title] => I am a post ),[1] => Array ( [id] => 2 [title] => I am a another post ) ) ) 问题是其中一个帖子分为两类.我想也有这方面的信息. 解决方法
我正在离开我的另一个答案,因为它包含了许多可能偶然发现它的好信息.至于更优雅地解决你的问题?你需要翻转它的头部并通过ad-hoc连接从Post模型中搜索,如下所示:
// From the CategoriesController $this->Category->Post->find('all',array( 'joins' => array( array( 'table' => 'categories_posts','alias' => 'CategoryFilter','type' => 'inner','conditions' => array( 'CategoryFilter.post_id = Post.id' ) ),array( 'table' => 'categories','alias' => 'CategoryUriFilter','conditions' => array( 'CategoryUriFilter.id = CategoryFilter.category_id' ) ) ),'conditions' => array( 'CategoryUriFilter.uri' => $uri ),'contain' => array('Category') )); 返回的数组格式有点不同,但它应包含您要查找的所有数据. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |