2012-06-12 35 views
0

我认为这将是一件比较常见的事情,但我无法在任何地方找到示例,关于find()的食谱本节内容并不清楚。也许这只是简单的事情Cake假设你可以自己做。CakePHP根据用户ID查找用户查询

我在这里要做的是在Cake中根据传递给我的视图中数组的ID来检索用户的名称(而不是当前登录的用户...不同的用户)。

下面是我在控制器中已经有了:

public function user_lookup($userID){ 
    $this->User->flatten = false; 
    $this->User->recursive = 1; 
    $user = $this->User->find('first', array('conditions' => $userID)); 
    //what now? 
} 

在这一点上,我甚至不知道我是不是在正确的轨道上。我认为这将返回与用户的一个数组数据,但我该如何处理这些结果?我怎么知道阵列的样子?我只是return($cakeArray['first'].' '.$cakeArray['last'])?我不知道...

帮助?

回答

2

您需要使用set来获取返回的数据,并使其可以在视图中作为变量访问。 set是将数据从控制器发送到视图的主要方式。

public function user_lookup($userID){ 
    $this->User->flatten = false; 
    $this->User->recursive = 1; 

    // added - minor improvement 
    if(!$this->User->exists($userID)) { 
     $this->redirect(array('action'=>'some_place')); 
     // the requested user doesn't exist; redirect or throw a 404 etc. 
    } 

    // we use $this->set() to store the data returned. 
    // It will be accessible in your view in a variable called `user` 
    // (or what ever you pass as the first parameter) 
    $this->set('user', $this->User->find('first', array('conditions' => $userID))); 

} 


// user_lookup.ctp - output the `user` 
<?php echo $user['User']['username']; // eg ?> 
<?php debug($user); // see what's acutally been returned ?> 
manual

以上(这是基本的蛋糕的东西,所以可能是值得拥有的好读)

+1

Upvoted,因为它是正确的答案,但你可能想不查询数据库两次这样一个简单操作。更简洁的方法是执行'$ user = $ this-> User-> find(...)',然后在空($ user)'时重定向,否则设置为view。此外,您的链接指向1.3版本的手册,而问题标签为2.0。 –