在 cakephp 2.1 上,我有两个表: qca 通过两个表上的字段 emp_number 属于员工。
qca model belongsTo : (请注意foreignKey)
public $actsAs = array('Containable');
var $belongsTo = array('Dir',
'Employee' => array(
'className' => 'Employee',
'foreignKey' => 'emp_number')
);
员工模型:
public $actsAs = array('Containable');
在我的控制器的查找中,我使用“包含”来根据 qca 表中的 emp_number 检索员工信息。
$hoursvalues = $this->Qca->find('all', array('conditions' => $conditions,
'fields' => array('Qca.emp_number', 'Sum(CASE WHEN Qca.qca_tipcode = 1 THEN 1 END) AS Qca__comps', 'Sum(qca_end - qca_start) as Qca__production', 'Sum(Qca.qca_durend) as Qca__idle'),
'contain' => array(
'Employee' => array(
'fields' => array('emp_number', 'emp_ape_pat', 'emp_ape_mat', 'emp_ape_mat'))),
'group' => array('Qca.emp_number'),
));
但是,执行的sql语句显示:
LEFT JOIN `devopm`.`employees` AS `Employee` ON (`Qca`.`emp_number` = `Employee`.`id`)
而
Employee
. id
应该是Employee
。emp_number
这是完整的sql语句:
SELECT `Qca`.`emp_number`, Sum(CASE WHEN Qca.qca_tipcode = 1 THEN 1 END) AS Qca__comps, Sum(qca_end - qca_start) as Qca__production, Sum(`Qca`.`qca_durend`) as Qca__idle, `Employee`.`emp_number`, `Employee`.`emp_ape_pat`, `Employee`.`emp_ape_mat`, `Employee`.`id` FROM `devopm`.`qcas` AS `Qca` LEFT JOIN `devopm`.`employees` AS `Employee` ON (`Qca`.`emp_number` = `Employee`.`id`) WHERE `Qca`.`dir_id` = 63 AND FROM_UNIXTIME(`Qca`.`qca_start`, '%Y-%m-%d') >= '2012-07-18' AND FROM_UNIXTIME(`Qca`.`qca_start`, '%Y-%m-%d') <= '2012-07-18' GROUP BY `Qca`.`emp_number`
这会导致为 Employee 返回 null 值:
array(
(int) 0 => array(
'Qca' => array(
'emp_number' => 'id3108',
'comps' => '2',
'production' => '7784',
'idle' => '529'
),
'Employee' => array(
'emp_ape_pat' => null,
'emp_ape_mat' => null,
'id' => null
)
),
注意:我还有其他“包含”实例正在工作(一个默认 id = tableName.id)。我想知道 belongsTo ('foreignKey' => 'emp_number') 上的 foreignKey 是否不利于 'contain' 工作?
你能帮我吗?
太感谢了。
(我找到了一种解决方法,但大大减慢了查询速度(它复制了左连接并且永远需要)
$joins = array(
array('table' => 'publication_numerations',
'alias' => 'PublicationNumeration',
'type' => 'LEFT',
'conditions' => array(
'Publication.id = PublicationNumeration.publication_id',
)
)
);
$this->Publication->find('all', array('joins' => $joins));