hasMany reduced to hasOne in CakePHP

廉价感情. 提交于 2020-01-02 10:18:13

问题


Basically I have following models in CakePHP:

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

I have set up following relation: User hasMany Photo.

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 the first record in the Photo table which matches a certain user_id.


回答1:


You could also use the Containable behaviour and then set up something like:

$this->User->find(
    'all', 
    array(
        'contains' => array(
            'Photo' => array(
                'order' => 'rand()',
                'limit' => 1
            )
        )
    )
);

You should then get something like

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

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

)




回答2:


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]



回答3:


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'].




回答4:


You'd do something like:

$user = $this->User->find('first', array('conditions' =>
                array('username'=>$this->data['User']['username'],
                      'active'=>true) ));


来源:https://stackoverflow.com/questions/4047737/hasmany-reduced-to-hasone-in-cakephp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!