2011-07-29 34 views
6

我是新來的蛋糕,並試圖找到檢索屬於一個$ ID的特定領域的最佳解決方案:CakePHP的:檢索特定表中的字段在控制器

這是我的看法功能在我的崗位控制器

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)); 
} 

在發佈表中,有一個user_id外鍵。我需要檢索屬於這個Post $ id的這個特定字段。

我讀功能的發現(「所有),閱讀(),或通過在視圖只是下降的非常規會議:

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

什麼是做到這一點的最好方式,我喜歡的是檢索控制器中的字段。謝謝!

回答

18

CakePHP有功能應該做到這一點。

$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

第二個選擇是使用找到功能,只返回幾個字段,如果你不希望整個Post對象。下面還顯示了使用條件而不是設置當前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

+0

感謝Ryan的兩種選擇,它的作用就像一個魅力! – ChrisDK

+0

太好了。使用CakePHP,find和field函數一直在使用,所以值得一讀,包括複雜的查找條件:http://book.cakephp.org/view/1030/Complex-Find-Conditions – Ryan

+0

感謝Ryan,會檢查出來。只需要在Cake 2.0中用FindQuery替換Find() – ChrisDK

1
$this->Post->id = $id; 
$this->Session->write('example',$this->Post->field('user_id')); 
+1

不知道'Model-> field()'方法。感謝您的信息。應該可以通過Cake API挖掘更多...但是很可惜。 – cspray

+0

是的,還有'saveField('field_name',value)';) –

0

試試這個,因爲我不知道是哪場(S),你需要我提供了使用魔法查找類型的實例字段設置陣列:

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

或多個記錄

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

*注意第二個例子除非在posts.title列中有多個標題名稱爲「The title」的標題,否則沒有多大意義。