我的分类模型:
class Category extends AppModel {
public $displayField = 'name';
// public $actsAs = array('Containable');
public $hasAndBelongsToMany = array(
'Post' => array(
'className' => 'Post',
'joinTable' => 'categories_postss',
'foreignKey' => 'category_id',
'associationForeignKey' => 'post_id',
'unique' => 'keepExisting'
)
);
}
$params['contain'] = array('Post' => array(
'limit'=> 3));
pr($this->Category->find('first',$params)); exit;
无论极限如何,它都会获取所有帖子。 我想做什么:
我有这个页面,我列出了所有类别和最新的5个相关帖子。 我想将关联的模型限制为仅5行。
有什么想法吗?
答案 0 :(得分:2)
此问题的最可能原因是根本没有使用可包含的行为。
比较,对于下面的代码示例:
$results = $this->Category->find('first', array(
'contain' => array(
'Post' => array(
'limit' => 3
)
)
));
如果没有可包含的行为,它将生成以下查询:
SELECT ... FROM `crud`.`categories` AS `Category` WHERE 1 = 1 LIMIT
SELECT ... FROM `crud`.`posts` AS `Post`
JOIN `crud`.`categories_posts` AS `CategoriesPost` ON (...)
使用可包含的行为,它将生成以下查询:
SELECT ... FROM `crud`.`categories` AS `Category` WHERE 1 = 1 LIMIT
SELECT ... FROM `crud`.`posts` AS `Post`
JOIN `crud`.`categories_posts` AS `CategoriesPost` ON (...) LIMIT 3
鉴于此(以及问题中的代码),检查AppModel在$actsAs
中是否具有可包含的行为:
<?php
// app/Model/AppModel.php
class AppModel extends Model {
public $actsAs = array('Containable');
}
或者,或者可能另外,您可能更愿意放置limit in the association definition - 为此,只需定义“限制”键:
class Category extends AppModel {
public $hasAndBelongsToMany = array(
'Post' => array(
'limit' => 100, // default to a high but usable number of results
)
);
}
答案 1 :(得分:1)
hasAndBelongsToMany
关系对我来说似乎没用。我认为您只需要Category hasMany Post
和Post belongsTo Category
关系。将category_id
添加到posts
表。制作两个模型actAs containable
。
发布模型
class Post extends AppModel {
public $actsAs = array('Containable');
var $belongsTo = array(
'Category' => array(
'className' => 'Category',
'foreignKey' => 'category_id'
),
// ... more relationships
);
类别模型
class Category extends AppModel {
public $actsAs = array('Containable');
var $hasMany = array(
'Post' => array(
'className' => 'Post',
'foreignKey' => 'category_id'
),
// ... more relationships
);
分类控制器
class CategoriesController extends AppController {
public $paginate = array(
'Category' => array(
'contain' => array(
'Post' => array(
'limit' => 3
), // end Post
) // end Category contain
) // end Category pagination
); // end pagination
public function index() {
// for paginated results
$this->set('categories', $this->paginate());
// for find results
$this->Category->contain(array(
'Post' => array(
'limit' => 3
)
));
$this->set('categories', $this->Category->find('all'));
}