CakePHP hasOne 关联条件

标签 cakephp

您好,我正在构建只有一张个人资料图片的用户模型,这是图像模型的示例。我希望 hasOne 的条件仅包含 Image.id 等于用户表中的“图片”列的图像。我知道有问题......这是代码的相关部分。

    var $hasOne = array(
            'ProfileImage' => array(
                    'className' => 'Image',
                    'conditions' => array('ProfileImage.id' => 'User.picture'),
                    'dependent' => false,
                    'foreignKey' => 'user_id',
            )
    );

我的条件有什么问题吗?如何指定 ProfileImage.id 等于用户模型中的图片列?谢谢!

最佳答案

如果外键(图片)位于 User 模型中,那么您的关联应该是 User ownsTo Image。如果图像一次只能由一个用户使用,则相反,图像有一个用户。如果一个图像可以被多个用户使用,那么它就是 Image hasMany User。

但是,如果图像一次只能由一个用户使用,则更好的数据结构是向 images 表添加一个 user_id 列。然后你就有了一个 User hasOne Image/Image ownsTo User 关系。

您不需要条件,只需要foreignKey


澄清问题后,您的情况需要如下所示:

'conditions' => array('ProfileImage.id = User.picture')

否则,Cake 认为 ProfileImage.id 应等于字符串 "User.picture"

关于CakePHP hasOne 关联条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6989602/

相关文章:

cakephp $this->request-is ("post") 仅对一种形式返回 false,很奇怪吗?

cakephp - 有 CakePHP PayPal 插件吗?

php - CakePHP 为每个请求添加公共(public)代码

internet-explorer - cakephp 在使用 Safari 和 Internet Explorer 时丢失 session

php - CakePHP 3.1 patchEntity 在清洁时总是将 belongsToMany 关联标记为脏

php - Security::hash() 不返回相同的哈希值

authentication - CakePHP 2 Auth 不工作 - Blowfish

cakephp - 在 Ubuntu 10.4 中运行 CakePHP 时遇到文件权限错误

未检索到 CakePHP 可包含模型

cakephp - 在 CakePHP 上设置新的 cookie