pkk
pkk

Reputation: 353

Convert a hasMany to hasOne in cakephp

I have 2 table users and galleries and the relationship is like User hasMany Gallery.But in some situation while querying on User model i want to get the latest Gallery row ie gallery with id 2 instead of multiple row.

Array
(
    [User] => Array
        (
            [id] => 100
            [username] => pradeepta
        )

    [Gallery] => Array
        (
            [0] => Array
                (
                    [id] => 1
                    [user_id] => 100
                    [photo] => 1111.jpg
                )
            [1] => Array
                (
                    [id] => 2
                    [user_id] => 100
                    [photo] => 222.jpg
                )
        )            
)

I want the result should be like this

Array
    (
        [User] => Array
            (
                [id] => 100
                [username] => pradeepta
            )

        [Gallery] => Array
            (
                                               
                [id] => 2
                [user_id] => 100
                [photo] => 222.jpg
            )
                        
    )

Upvotes: 2

Views: 262

Answers (2)

drmonkeyninja
drmonkeyninja

Reputation: 8540

The relationship still needs to be a hasMany, but you want to change the conditions for the query. If you use a join statement you can limit the results returned:-

$this->User->find(
    'first',
    array(
        'fields' => array(
            'User.*',
            'Gallery.*'
        ),
        // Join on the galleries table
        'joins' => array(
            array(
                'table' => 'galleries',
                'alias' => 'Gallery',
                'type' => 'LEFT',
                'conditions' => array(
                    'Gallery.user_id = User.id'
                )
            )
        ),
        // Order by newest galleries first
        'order' => array(
            'Gallery.id' => 'DESC'
        ),
        // Make sure we only return one instance of each user
        'group' => array(
            'User.id'
        )
    )
);

Upvotes: 1

Pradeepta
Pradeepta

Reputation: 458

User this association in your User model

public $hasOne = array(        
        'Gallery' => array(
            'className' => 'Gallery',
            'foreignKey' => 'user_id',
            'order' => array('Gallery.id' => 'DESC')
        ),
    );

Upvotes: 0

Related Questions