views:

33

answers:

4

hi, basically i have following models in CakePHP:

User(id, username) Photo(id, user_id, path)

i have set up following relation: User hasMany Photo.

now, on one screen, i would like to list users, and show random photo next to each user. i tried setting up following relation:

User hasOne SamplePhoto (where SamplePhoto is just Photo model)

but when user has two photos for instance, he is listed twice on the list.

basically my question is: can you reduce hasMany relation to hasOne, without adding any fields to table schema presented above? i would like to tell cake - find first record in Photo table which matches witch certain user_id.

A: 

You'd do something like:

$user = $this->User->find('first', array('conditions' =>
                array('username'=>$this->data['User']['username'],
                      'active'=>true) ));
Eduardo
This will find the first User
Leo
+2  A: 

if you do a find like $this->User->read(null,$id), the return will be an array that looks something like:

Array
(
    [User] => Array
        (
            [id] => 121
            [username] => tom
        )

    [Photo] => Array
        (
            [0] => Array
                (
                    [id] => 123
                    [user_id] => 121
                    [path] => Somewhere
                )
            [1] => Array
                (
                    [id] => 124
                    [user_id] => 121
                    [path] => SomeOtherPlace
                )
        )            
)

From this array you can pick the photo however you like, be it the first:

$this->data['Photo'][0]

the last:

$this->data['Photo'][count($this->data['Photo'])]

an explicit record:

$this->data['Photo'][3]

or by some random means:

$this->data['Photo'][$rnd]
Leo
+2  A: 

Don't make this more complicated than it needs to be. :)

$data = $this->User->Photo->find('first',
        array('conditions' => array('Photo.user_id' => $id)));

Gives you a photo in $data['Photo'] with the user attached in $data['User'].

deceze