分页与协会的hasMany CakePHP的
-
22-09-2019 - |
题
我有两个表:
和参赛者票数 选手的hasMany投票
我试图做一个计数(Vote.id)作为投票数,所以我可以将其放置在 记录集,只是分页他们,但我不知道在哪里把它。 我做的田野阵列上,但它给了我票的总数 无论选手他们属于
在投票链接在一起的参赛者记录所以我 没有对我的看法,我做了计数($选手[投票]),但是这不能成为 分页和我的客户希望能够通过对参赛者进行排序 票。
有没有一种方法可以让我做这样的事情对我的看法:
排序( '投票', '计数(投票)'); ?>
还是我必须要创建一个查询,其中做了计数所有的选票 其中Contestant.id = Votes.contestant_id?
控制器参赛者:
function index() {
$page = 'Contestants';
$this->set('page', $page);
$this->paginate =
array(
'order' => 'id ASC',
'contain' => array(
'Vote' => array(
'fields' => array("Vote.contestant_id",'Vote.id')
)
)
$conditions ["Contestant.active"] = 1;
$this->set('contestants', $this->paginate('Contestant',
$条件)); }
解决方案 2
从CakePHP不中可容纳行为支持组由我尝试了不同的方法。创建投票模型,而不是(所有这一切都是在参赛者控制器来完成的)PAGINATE VAR:
var $paginate = array(
'Vote'=>array(
'limit'=>5,
'fields' => array(
'Contestant.*, count(Vote.contestant_id) as Contestant_votes, Vote.id'
),
'group' => array(
'Vote.contestant_id'
),
'order' => array(
'Contestant_votes Desc'
)
),
'Contestant'=>array(
'limit'=>5,
'order' => array(
'Contestant.id Desc'
)
)
);
现在在我的控制器我做到以下几点:
function index() {
$page = 'Contestants';
$this->set('page', $page);
$conditions ["Contestant.active"] = 1;
$this->set('contestants', $this->paginate($this->Contestant->Vote,$conditions));
}
现在的选手是由它们的总投票理货有序,虽然我还是不能图如何放置Contestant_votes作为分页程序变量,因为在记录中设置它在它的一个阵列本身,而不是在任何模式阵列用于进行分页。
感谢马特·哈金斯你的方法是一个使我这个解决方案。
其他提示
查核在这个问题deceze的反应: CakePHP的数学算字段一>
基本上你想要做这样的事我猜测:
'contain' => array(
'Vote' => array(
'fields' => array('SUM(Vote.id) AS Contestant__votes'),
'group' => array('Vote.contestant_id'),
)
)
增加:您是否也想通过投票(总票数)升序或降序排序?如果是的话,你可以不被CakePHP的默认分页方法做到这一点很容易。
有关,你需要一个小调整。以下是有关这一招细节: CakePHP的高级分页 - 排序衍生字段
希望你会发现它有用。
由于 阿德南
有关您定义的特定关系,你需要通过的反缓存。
您需要在您的contestants
表来定义一个新的领域:vote_count
。然后,在你的投票模式,你需要稍微更新$belongsTo
定义:
class Votes extends AppModel
{
var $belongsTo = array(
'Contestant' => array( 'counterCache' => true )
);
}
现在,任何时候一个投票保存记录时,父参赛者的vote_count
字段将被更新。现在,你可以简单地排序Contestant.vote_count
,就像任何其他选手现场:
class ContestantsController extends AppController
{
// Controller stuff that comes before...
function index()
{
$this->paginate = array( 'Contestant' => array(
'conditions' => array( 'Contestant.active' => 1 ),
'order' => array( 'Contestant.vote_count' => 'DESC' ),
));
$contestants = $this->paginate('Contestants');
$this->set( compact('contestants'));
}
// Controller stuff that comes after...
}