CakePHP 2.3模型关联使用finderQuery可以与model ->read()工作,但不能与model ->


CakePHP 2.3 model association using finderQuery works with Model->read() but not with Model->find()

我几乎已经让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"

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

所以,在看了这篇文章之后,我想到了这个(我将只展示帐户模型)http://www.visuallizard.com/blog/2009/02/19/210:

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查询都是这样,这将会得到我的wick,因为我相信你们中的一些人可能会理解。

关于我在这里做了什么有线索吗?我是否误解了什么,或者这是一个CakePHP bug?

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

您似乎已经为帐户表中的foreignKey字段指定了正确的命名,但请确保在Postcode模型中指定'ref'为主键。关系如下所示:

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模型:

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

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

应该可以