hasMany reduced to hasOne in CakePHP

…衆ロ難τιáo~ 提交于 2019-12-06 04:29:14

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
            )
    )            

)

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]

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

You'd do something like:

$user = $this->User->find('first', array('conditions' =>
                array('username'=>$this->data['User']['username'],
                      'active'=>true) ));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!