【发布时间】:2019-10-15 10:12:42
【问题描述】:
CakePHP 3.7
我有 2 个模型表类如下:
/src/Model/Table/SubstancesTable.php/src/Model/Table/TblOrganisationSubstancesTable.php
MySQL中每张表的schema如下:
1.
mysql> describe substances;
+-------------+-----------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+-----------------------+------+-----+---------+----------------+
| id | mediumint(8) unsigned | NO | PRI | NULL | auto_increment |
| app_id | varchar(8) | NO | UNI | NULL | |
| name | varchar(1500) | NO | | NULL | |
| date | date | NO | | NULL | |
+-------------+-----------------------+------+-----+---------+----------------+
2.
mysql> describe tbl_organisation_substances;
+-------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+--------------+------+-----+---------+----------------+
| o_sub_id | int(255) | NO | PRI | NULL | auto_increment |
| o_id | int(255) | NO | MUL | NULL | |
| app_id | varchar(15) | YES | | NULL | |
| os_name | varchar(255) | YES | | NULL | |
| ec | varchar(35) | YES | | NULL | |
| cas | varchar(255) | YES | | NULL | |
| upload_id | int(100) | YES | | NULL | |
+-------------+--------------+------+-----+---------+----------------+
我编写了一个自定义查找器,它需要在这两个表之间执行JOIN。自定义查找器如下所示,位于SubstancesTable.php:
public function findDistinctSubstancesByOrganisation(Query $query, array $options)
{
$o_id = $options['o_id'];
$query = $this->find()->select('id')->contain('TblOrganisationSubstances')->where(['TblOrganisationSubstances.o_id' => $o_id]);
return $query;
}
每个表都有一个app_id 列,这是链接两个表的外键。
最初我遇到了一个错误:
没有在 Substances 上定义 TblOrganisationSubstances 关联。
这是有道理的,因为没有定义。
所以在SubstancesTable.php 我已经定义了这个:
$this->setPrimaryKey('id');
// ...
$this->belongsTo('TblOrganisationSubstances', [
'foreignKey' => 'app_id',
'joinType' => 'INNER'
]);
但这会产生以下 SQL 语句:
SELECT Substances.id AS `Substances__id` FROM substances Substances INNER JOIN tbl_organisation_substances TblOrganisationSubstances ON TblOrganisationSubstances.o_sub_id = (Substances.app_id) WHERE TblOrganisationSubstances.o_id = :c0
这是行不通的,因为TblOrganisationSubstances.o_sub_id = (Substances.app_id) 是错误的。它需要基于app_id JOIN,也就是说应该是:
TblOrganisationSubstances.app_id = (Substances.app_id)
我还尝试将 belongsTo 更改为 hasMany 关联(甚至不确定哪个是正确的!):
$this->hasMany('TblOrganisationSubstances', [
'foreignKey' => 'app_id',
]);
但加入似乎并没有发生。生成的 SQL 是:
SELECT Substances.id AS `Substances__id` FROM substances Substances WHERE TblOrganisationSubstances.o_id = :c0
我还尝试在TblOrganisationSubstances.php 中添加belongsTo 来尝试定义双方的关系:
$this->belongsTo('Substances', [
'foreignKey' => 'app_id',
'joinType' => 'INNER'
]);
同样,这不起作用。它生成没有连接的 SQL。
请有人帮忙提供正确的关联类型(hasMany vs belongsTo)以及如何根据app_id(链接两个表的外键)执行连接。
【问题讨论】:
标签: php cakephp cakephp-3.x