CakePHP:在控制器中检索特定的表字段 [英] CakePHP: Retrieve specific table field in controller

查看:121
本文介绍了CakePHP:在控制器中检索特定的表字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am new to Cake and tried to find the best solution to retrieve a specific field belonging to an $id:

这是我的Post控制器中的view函数

This is my view function in my Post controller

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表中,有一个user_id外键。我需要检索属于此帖子$ id的特定字段。

In the post table, there is a user_id foreign key. I need to retrieve this specific field belonging to this Post $id.

我读过有关find('All),read()的函数,或者只是在其中删除了一个非常规的会话通过以下方式查看视图:

I read about functions as find('All), read() or just drop an unconventional session in the view through:

$session->write('example') = $post['Post']['user_id];

最好的方法是什么,我的首选是在控制器中检索字段。谢谢!

What is the best way to do this, my preference is to retrieve the field in the controller. Thanks!

推荐答案

CakePHP具有一个 field 功能,应该可以做到这一点。

CakePHP has a field function which should do just that.

$this->Post->id = $id;
$user_id = $this->Post->field('user_id');

有关使用字段的更多信息,请参见: http://book.cakephp.org/2.0/en/models/retrieving-your-data.html #model-field

For more information on using field, see: http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#model-field

第二种选择是使用 find 函数,如果您不想的话,仅返回一些字段整个Post对象。下面还显示了使用条件而不是设置当前Post。

A second option is to use the find function and returning only a few fields if you do not want the entire Post object. Also shown below is using a condition instead of setting the current Post.

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

有关查找的更多信息,请访问: http://book.cakephp.org/2.0/en/models/retrieving-your-data.html

More information on find is available at: http://book.cakephp.org/2.0/en/models/retrieving-your-data.html

这篇关于CakePHP:在控制器中检索特定的表字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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