php - 在 CakePhp 中,如何只从我的数据库中检索一列?

标签 php cakephp cakephp-2.0 cakephp-model

我有一个非常简单的应用程序,只有 1 个表,每行包含一个词、它的定义和一个示例。

定义和示例字段是 varchars(5000)。

在每个页面上,我都有一个显示单词列表的边栏。在一定数量的单词后,我开始收到以下错误:

Error: Allowed memory size of 33554432 bytes exhausted

Controller 中设置元素中使用的变量的代码:

$this->set('allWords', $this->Word->find('all', array('order' => array('Word.text ASC'))));

我怀疑find方法读入了所有的行数据,包括定义和例子,我现在真的不需要,这导致了错误。

有没有办法只读取 id 和单词,而不是每行的定义和示例值?

更新

在我的元素中,我遍历 $allWords 数组以打印出每个单词以及一个链接:

echo '<h3>Words ('.count($allWords).')</h3>';
echo $this->Html->link('Add new', array('controller' => 'words', 'action' => 'add'));
echo '<br/><br/>';

foreach($allWords as $thisWord)
{
    echo $this->Html->link($thisWord['Word']['text'], array('controller' => 'words', 'action' => 'edit', $thisWord['Word']['id']));

    if( ($thisWord['Word']['example'] == '') || ($thisWord['Word']['definition'] == '') )
    {
        echo '&nbsp;' . $this->Html->image('warning.png');
    }
    echo '<br \>';
}

看来,如果我注释掉 foreach 循环的内部部分,我不会得到内存错误。

本例中的 SQL 输出为:

SELECT `Word`.`id` FROM `idioms`.`words` AS `Word` WHERE 1 = 1 ORDER BY `Word`.`text` ASC`

有 339 行受到影响。

谢谢!

最佳答案

传递关联数组中的字段参数

'fields'=>array('Word.id','Word.word')

你能试试这个吗?

$this->set('allWords', $this->Word->find('all', array('order' => array('Word.text ASC'), 'fields'=>array('Word.id','Word.word') )));

获取更多信息 http://book.cakephp.org/2.0/en/models/retrieving-your-data.html

关于php - 在 CakePhp 中,如何只从我的数据库中检索一列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13485159/

相关文章:

php - 非 DISTINCT 结果集的 SELECT 查询分组/合并

php - 使用 PostgreSQL 在 Yii2 上的用户时区问题

php - SMTP 连接失败并激活 TLS

cakephp - 是否建议在数据库上存储城市列表等内容?

javascript - jQuery 无法与 cakephp 2.0 一起使用

PHP 插入多个空格

php - 在另一个表中发生不相关的插入操作后,Mysql 行被删除

cakephp 单选按钮字段已选择

cakephp - 单页 cakephp 上具有相同型号名称的多个表单

css - CakePHP 2.0 表助手