CakePHP正在将MySQL整数转换成字符串...混乱rand()函数 [英] CakePHP is converting MySQL integers into strings... messing up rand() function

查看:127
本文介绍了CakePHP正在将MySQL整数转换成字符串...混乱rand()函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用CakePHP从我的数据库中随机抽取一些数据。这是我的函数:

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

//随机启动
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);
//随机排序结束

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

问题是,Cake发送到DB的查询总是 到RAND()部分,发送MySQL到一个hissy契合:

  ORDER BY RAND(`1235123412341 `)

测试一个手动查询,它工作得很好,这:

  ORDER BY RAND(1235123412341)

有什么办法让蛋糕回退自动格式化吗?

解决方案


我放置的任何东西RAND()函数被转储到字符串引号中。


否,这是不正确的。如果它使用字符串引号,那么它会工作正常,但反引号不是字符串引号。问题是,CakePHP正在引用数字,就像它是一个列名。请尝试使用单引号引用该值:

 RAND('%d')



这将导致生成以下SQL:

  ORDER BY RAND('1235123412341')

不包括引号。


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.

解决方案

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.

这篇关于CakePHP正在将MySQL整数转换成字符串...混乱rand()函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆