繁体   English   中英

CakePHP中的命名约定和连接

[英]Naming convention and joins in CakePHP

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

数据库描述:

用户表<user_id(主键),fname,lname>。

邮件表<mail_id(主键),从(外键到user_id)到(外键到user_id),内容,打开>。

我的问题:

1)根据惯例,外键应该被称为相关表+'_ id'。 如果有两个与同一个表相关的外键,我应该如何调用列。 喜欢来自和来自邮件表。

2)我想在两个表之间做一个内部JOIN。 就像是:

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

但我不知道该怎么做。

当您需要对同一个表执行两个关系时,您将需要覆盖默认约定。 在你的例子中,我会制作2个外键。 一个名为sender_id ,另一个名为recipient_id 然后你会像他们一样加入模型:

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

我自己不是专家,但在CakePHP网站上关注信息将进一步帮助您: 多关系到同一模型

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM