0

我几乎可以让 Cake 在这里做我想做的事,但并不完全,我认为这是因为我的知识存在差距。

我已将英国邮政编码的数据库表导入到我的 cakePHP 应用程序中。这是结构:

CREATE TABLE IF NOT EXISTS `postcodes` (
  `ref` varchar(6) NOT NULL DEFAULT '',
  `area` varchar(50) NOT NULL DEFAULT '',
  `uk_region` varchar(4) NOT NULL,
  `lat` decimal(6,4) NOT NULL DEFAULT '0.0000',
  `long` decimal(5,4) NOT NULL DEFAULT '0.0000',
  PRIMARY KEY (`ref`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

这是该表中 CSV 格式的一行。

"AB10","Aberdeen","SCOT","57.1350","-2.1170"

“帐户”和“订单”需要能够从“邮政编码参考”中查找这些详细信息

因此,在阅读了这篇文章http://www.visuallizard.com/blog/2009/02/19/210之后,我想出了这个(我将只展示 Account 模型):

class Account extends AppModel {
    public $hasOne = array('Postcode' => 
        array(
          'className' => 'Postcode', 
          'finderQuery' => 'SELECT Postcode.* FROM accounts, postcodes AS Postcode WHERE accounts.id = {$__cakeID__$} AND accounts.postcode_ref = Postcode.ref', 'foreignKey' => false
));

}

现在,如果我执行其中“16”是测试帐户 ID 的其中任何一个:

$this->Account->read(null, 16);
$this->Account->find('first', array('conditions' => array('Account.id' => 16)));

检索数据一切都很好。但是,如果我这样做:

$this->Account->find('all', array('conditions' => array('Account.id' => 16)));

我得到了一个结果正确但 2,821 次的数组;这是有多少个邮政编码条目。

将其从 $hasOne 更改为 $hasMany 也只返回一次结果,但它在 $result['Postcode'][0] 内,因为所有 hasMany 查询都是如此,我相信你们中的一些人会这样可以理解。

关于我在这里做了什么的任何线索?我是否误解了什么或者这是一个 CakePHP 错误?

4

1 回答 1

3

你最好的选择是“扭转”这种关系;帐户属于邮政编码。由于一个帐户只能有一个邮政编码,基本上它“属于”一个邮政编码,每个邮政编码(区域)可以有(包含)多个帐户。

您似乎已经为您的帐户表中的 foreignKey 字段正确命名,但请务必指定“ref”作为 Postcode 模型中的主键。关系将如下所示;

Account extends AppModel {
    public $belongsTo = array(
        // additional settings are probably not
        // required because postcode_ref follows the
        // CakePHP conventions, so foreignKey will
        // automatically be detected
        'Postcode',
    );

}

和邮政编码模型:

Postcode extends AppModel {
    // Important because of non-standard PK name
    public $primaryKey = 'ref';


    public $hasMany = array(
        'Account',
    );
}

这应该可以工作

于 2013-03-15T20:29:07.067 回答