hasMany简化为hasOne在CakePHP [英] hasMany reduced to hasOne in CakePHP

查看:168
本文介绍了hasMany简化为hasOne在CakePHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上我在CakePHP中有以下模型:



用户(id,用户名)
照片(id,user_id,路径)
$ b

我设置了以下关系:用户有多张照片。



现在,在一个屏幕上,我想列出用户,每个用户旁边的随机照片。我尝试设置以下关系:



用户hasOne SamplePhoto(其中SamplePhoto只是照片模型)



用户有两张照片,他在列表中列出了两次。



基本上我的问题是:你可以减少hasOany与hasOne的关系,上面提到过?

解决方案

您也可以使用< a href =http://book.cakephp.org/view/1323/Containable =nofollowtitle =CakePHP Cookbook中的可控制行为>可容纳行为,然后设置如下: / p>

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


);

您应该会得到类似

  Array 

[User] => Array

[id] => 121
[username] > tom


[Photo] => Array

[0] => Array
] => 123
[user_id] => 121
[path] =>某处


pre>


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.

解决方案

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

)

这篇关于hasMany简化为hasOne在CakePHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆