Search code examples
cakephpgallerymodel-associations

Cakephp 2.x find first entry of releated model


I know that i can easily find related model-data through model associations, if I select a single entry. But what I want to do is to get the first image as a thumb for the galery, when I use find('all') for the index-page.

My relations (Galleries are named Albums) are:

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

and:

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

Solution

  • EDIT : This should worked I tested it on my own!

    Before your query add the following lane to specify the recursivity.

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

    This way, it will also send the Pictures data. Then in your model associations, you can specify to only return the first image with the Album if that's what you want!

    Just add 'limit' => '1', in your hasMany => Comments array, in Album Model.

    Then you can iterate in your view doing

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

    EDIT2: I've just see you can also do

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