2012-08-15 81 views
0

我知道如果選擇單個條目,我可以通過模型關聯輕鬆找到相關的模型數據。但是,當我使用find('all')作爲索引頁面時,我想要做的是將第一張圖像作爲Galery的縮略圖。Cakephp 2.x找到相關模型的第一個條目

我的關係(畫廊被命名爲相冊)是:

//Album-Model 
public $hasMany = array(
    'Picture' => array(
     'className' => 'Picture', 
     'foreignKey' => 'album_id', 
     'dependent' => true, 
     'conditions' => '' 
    ) 
); 

和:

public $belongsTo = array(
    'User' => array(
     'className' => 'User', 
     'foreignKey' => 'user_id', 
     'conditions' => '', 
     'fields' => '', 
     'order' => '' 
    ), 
    'Album' => array(
     'className' => 'Album', 
     'foreignKey' => 'album_id', 
     'conditions' => '', 
     'fields' => '', 
     'order' => '' 
    ) 
); 

回答

2

編輯: 這應該工作,我測試了我自己!

在查詢之前添加以下泳道以指定遞歸性。

$this->Albums->recursive = 1; 
$this->set('Albums', $this->Album->find('all')); 

這樣,它也會發送圖片數據。然後在你的模型關聯中,你可以指定只返回第一張圖片與相冊,如果這是你想要的!

只需在您的hasMany => Comments數組中添加'limit' => '1',即可。

然後你就可以在您的視圖做

foreach($Albums as $Album){ 
    $Album['Album']; // ALBUMS info do whatever 
    $Album['Picture']; // The thumbnail 
} 

EDIT2迭代:我剛剛看你也可以做

$this->Album->find('all', array('recursive' => 1)); 
+0

我知道,但我想找到它所有的畫廊時 - 例如 - 使用:$ this-> Album-> find('all'); – 2012-08-15 20:15:36

+0

當我使用find('all')時,沒有與模型相關的圖片。只有當我使用>> $ this-> set('album',$ this-> Album-> read(null,$ id))<<。這就是爲什麼我認爲我的modell設置正確。也許它顯示這種行爲來節省內存? – 2012-08-15 20:32:46

+0

這應該現在工作 – 2012-08-15 21:02:38