2009-12-28 42 views
3

就在几天前,我发现了这个叫做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. 

但我不知道该怎么做。

+1

虽然在约定的主题上,您应该简单命名主键“id”,而不是“user_id”和“mail_id”。 :) – deceze 2009-12-28 23:22:42

回答

1

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

+0

嗨, 感谢您的回复。我看过教程,在他们的例子中,他们写了一个$ this-> Recipe-> find()调用的示例结果。 但我真的无法知道什么是写在食谱 - >找到() – special0ne 2009-12-28 14:06:03

+0

然后你可能已经试验了conplex查找以及(http://book.cakephp.org/view/73/Retrieving-Your-Data#复杂-FIND-条件-74)。 如果失败,可以使用$ this-> Recipe-> query($ sqlStatement)。 – 2009-12-28 14:30:52

+0

Recipe :: find()函数是从父类继承的,因此您不必编写它。它是为你写的。如果您的意思是传递给函数的参数,那么在手册中有很好的文档记录。我建议你做蛋糕教程,开始完成,这应该可以帮助你解决这些基本问题。 – 2009-12-28 16:32:35

4

当你需要做两个关系同桌,你需要重写默认的惯例。在你的例子中,我会做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))); 
?>