2012-06-12 33 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。 –