CakePHP:检索控制器中的特定表字段

CakePHP:检索控制器中的特定表字段,cakephp,Cakephp,我是Cake的新手,试图找到检索属于$id的特定字段的最佳解决方案: 这是我的Post控制器中的查看功能 function view($id = null) { if (!$id) { $this->Session->setFlash(__('Invalid post', true)); $this->redirect(array('action' => 'index')); } $this->set('pos

我是Cake的新手,试图找到检索属于$id的特定字段的最佳解决方案:

这是我的Post控制器中的查看功能

function view($id = null) {
    if (!$id) {
        $this->Session->setFlash(__('Invalid post', true));
        $this->redirect(array('action' => 'index'));
    }
    $this->set('post', $this->Post->read(null, $id));
}
在post表中,有一个用户id外键。我需要检索属于此Post$id的这个特定字段

我通过以下途径了解了函数find('All')、read()或只是在视图中删除一个非常规会话:

$session->write('example') = $post['Post']['user_id];
最好的方法是什么,我的首选方法是检索控制器中的字段。谢谢


CakePHP有一个字段函数,它应该可以做到这一点

$this->Post->id = $id;
$user_id = $this->Post->field('user_id');
有关使用字段的详细信息,请参阅:

第二个选项是使用find函数,如果不需要整个Post对象,则只返回几个字段。下面还显示了使用条件而不是设置当前Post

$this->Post->find('first', array(
  'conditions'=>array('id'=>$id),
  'fields'=>array('user_id')
));

有关查找的更多信息,请访问:

尝试此项,因为我不知道您需要哪些字段。我提供了一个使用Magic find类型的示例字段数组集:

$fields = ['title', 'body', 'created'];
$record = $this->Post->findById($id, $fields);
或多个记录

$recordSet = $this->Post->findAllByTitle('The title', $fields);

*请注意,第二个示例没有多大意义,除非posts.title列中有多个名称为“thetitle”的标题。

在CakePHP 3中,您可以使用
$this->Model->get()
获取实体,然后直接引用所需字段

$fieldValue = $this->ModelName->get($id)->fieldName;

不知道
Model->field()
方法。谢谢你的信息。可能应该更深入地研究Cake API……但是,唉,还有
saveField('field_name',value)
;)伟大的使用CakePHP,find和field函数一直都在使用,因此值得一读,包括复杂的find条件:谢谢Ryan,我会检查一下。刚才提到,在Cake 2.0中,Find()将被createQuery替换。感谢您的注意,考虑到我们的代码中经常使用“Find”,这是一个很大的语法变化。我真的很希望
field()
在Cake的文档中处于更高的位置。。。会节省很多时间。对于CakePHP 3.*,请尝试以下
->contain(['Languages'=>['fields'=>['BooksLanguages.book\u id','Languages.id']])。更多阅读
$fieldValue = $this->ModelName->get($id)->fieldName;