我有一个表'活动',列按其三个属性分组。现在我想获取从所有组中随机选择的活动ID。查询如下:
$act = $this->find('all', array('conditions' => $cond,
'limit' => $limit,
'fields' => array('count(*) as count, Activity.id as id'),
'page' => $page,
'group' => $group,
));
这些是我尝试过的,但都没有奏效。 1.创建一个应该有随机记录的自联接
$this->bindModel(array(
'belongsTo' => array(
'Random' => array(
'className' => 'Activity',
'order' => 'rand()',
'foreignKey' => 'id',
'fields' => 'Random.id'
)
)
));
这失败了,因为rand()命令被追加到最后,它只是随机化所有获取的活动。
添加了加入选项
'joins' => array(
array(
'table' => 'activities',
'alias' => 'Random',
'type' => 'LEFT',
'conditions' => array(
'Activity.id = Random.id'
),
'fields' => 'Random.id',
'order' => 'rand()'
)
这也不起作用,因为Cake
没有解析订单值请帮帮我
答案 0 :(得分:0)
假设您的查询有效:
$act = $this->find('all', array('conditions' => $cond,
'limit' => $limit,
'fields' => array('count(*) as count, Activity.id as id'),
'page' => $page,
'group' => $group,
'order' => 'rand()',
'limit' => '1' // if you only want one random activity ID
));
答案 1 :(得分:0)
好吧终于明白了。我们需要破解蛋糕php工作的方式。代替表名,我写了一个查询来获取随机排序的记录。另请注意,联接类型是'对'。左连接不会产生随机排序的列表
$activities = $this->find('all', array('conditions' => $cond,
'page' => $page,
'limit' => $limit,
'fields' => array('count(*) as count, Random.id as id, max(Activity.modified) as Modified'),
'group' => $group,
'order' => 'Modified desc',
'joins' => array(
array(
'table' => '(select * from activities order by rand())',
'alias' => 'Random',
'type' => 'RIGHT',
'conditions' => array(
'Activity.id = Random.id'
),
)
)
));