duandou2763 2011-01-29 08:17
浏览 67
已采纳

CakePHP正在将MySQL整数转换为字符串......弄乱了rand()函数

I want to grab a random sample of data out of my database using CakePHP. Here's my function:

function categories_list() 
{   
    $this->paginate['limit'] = 6;
    $this->paginate['order'] = '';
    $this->paginate['conditions'] = '';

    // Sort Randomly Start 
    if ($this->Session->check('Category.randomSeed')) 
    { 
        $seed = $this->Session->read('Category.randomSeed'); 
    } else { 
        $seed = mt_rand(); 
        $this->Session->write('Category.randomSeed', $seed); 
    } 
    $this->paginate['order'] = sprintf('RAND(%d)', $seed); 
    // Sort Randomly End 

    $this->set('cat_ajax_items', $this->paginate('Category')); 
}

The problem is, the query that Cake sends to the DB always does this to the RAND() portion, sending MySQL into a hissy fit:

ORDER BY RAND(`1235123412341`)

Testing on a manual query, it works just fine, and returns a sample when it's formatted like this:

ORDER BY RAND(1235123412341)

Is there any way to get Cake to back off of the autoformatting? Anything I put into that RAND() function gets dumped into string quotes.

  • 写回答

2条回答 默认 最新

  • duanlu8613 2011-01-29 08:21
    关注

    Anything I put into that RAND() function gets dumped into string quotes.

    No, this isn't correct. If it used string quotes then it would work fine, however backticks aren't string quotes. The problem is that CakePHP is quoting the number as if it were a column name. Try quoting the value using single quotes instead:

    "RAND('%d')"
    

    This should result in the following SQL being produced:

    ORDER BY RAND('1235123412341')
    

    This gives the same result as when you don't include the quotes.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度