![](/img/trans.png)
[英]In CakePhp, how can I retrieve the value of only one column from my database?
[英]In CakePhp, how can I retrieve only one column from my database?
我有一个非常简单的应用程序,有1个表,每行包含一个单词,它的定义和一个例子。
定义和示例字段是varchars(5000)。
在每个页面上,我都有一个显示单词列表的侧边栏。 在一定数量的单词后,我开始收到以下错误:
Error: Allowed memory size of 33554432 bytes exhausted
控制器中的代码,用于设置Element中使用的变量:
$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 ' ' . $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参数
'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
获取单个字段值列表的简单方法是使用find('list') :
$values = $this->find('list', array(
'fields' => array('id', 'text'),
// ^ what to use for key and value of `$values`
'order' => Word.text'
));
如果text
是相关模型的displayField ,则根本不需要指定字段,主键字段和显示字段是默认值:
$values = $this->find('list', array(
'fields' => array('id', 'text'),
'order' => Word.text'
));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.