代码之家  ›  专栏  ›  技术社区  ›  special0ne

cakephp中的命名约定和连接

  •  3
  • special0ne  · 技术社区  · 15 年前

    就在几天前我发现了这个奇迹 CakePHP 所以我对它很不感冒。 我需要构建一个邮件应用程序,因此我遵循了约定并创建了:

    数据库描述:

    用户表<用户id(主键)、fname、lname>。

    邮件表<邮件ID(主键),从(外键到用户ID),到(外键到用户ID),内容,已打开>。

    我的问题:

    1)根据约定,外键应该称为related table+“u id”。如果有两个外键与同一个表相关,我应该如何调用这些列。就像在邮件桌上来回。

    2)我想在两个表之间做一个内部连接。 类似于:

    SELECT user_id, mail_id 
    FROM users
    INNER JOIN mails
    ON users.user_id =mails.to AND mails.opened=false. 
    

    但我不知道怎么做。

    2 回复  |  直到 15 年前
        1
  •  4
  •   spelley    15 年前

    当需要对同一个表执行两个关系时,需要重写默认约定。在你的例子中,我会做两个外键。一个名字 森德里德 还有一个叫 受胎人 . 然后你可以像这样把他们加入模型:

    <?php
    
    class Mail extends AppModel {
        //The Associations below have been created with all possible keys, those that are not needed can be removed
        var $belongsTo = array(
            'UserSender' => array(
                'className' => 'User',
                'foreignKey' => 'sender_id',
                'conditions' => '',
                'fields' => '',
                'order' => ''
            ),
                'UserRecipient' => array(
                'className' => 'User',
                'foreignKey' => 'recipient_id',
                'conditions' => '',
                'fields' => '',
                'order' => ''
            ),
        );
    }
    ?>
    

    然后,为了满足您的条件,您可以这样引用它们:

    <?php
        $this->Mail->find(array('conditions'=>array('Mail.opened'=>false)));
    ?>
    

    …要筛选发送方和接收方,您的条件如下:

    <?php
        $this->Mail->find(array('conditions'=>array('UserSender.some_field'=>$someValue,
                                                    'UserRecipient.some_field'=>$someValue)));
    ?>
    
        2
  •  1
  •   Peter Mortensen icecrime    15 年前

    我自己不是专家,但以下cakephp网站的信息将进一步帮助您: Multiple-relations-to-the-same-model