CakePHP 3-未定义关联-即使看起来像是

时间:2019-06-12 13:15:54

标签: php cakephp-3.0 cakephp-3.x

我已经使用CakePHP 3.7烘焙了一个旧版应用程序

数据库包含3个表,如下所示:regulationsgroupsfilters。就应用程序而言,层次结构是:

  • 法规
      • 过滤器

表模式如下:

mysql> describe regulations;
+-------+---------------------+------+-----+---------+----------------+
| Field | Type                | Null | Key | Default | Extra          |
+-------+---------------------+------+-----+---------+----------------+
| id    | tinyint(3) unsigned | NO   | PRI | NULL    | auto_increment |
| name  | varchar(255)        | NO   |     | NULL    |                |
| label | varchar(255)        | NO   |     | NULL    |                |
+-------+---------------------+------+-----+---------+----------------+
4 rows in set (0.09 sec)

mysql> describe groups;
+---------------+-----------------+------+-----+---------+----------------+
| Field         | Type            | Null | Key | Default | Extra          |
+---------------+-----------------+------+-----+---------+----------------+
| id            | int(4) unsigned | NO   | PRI | NULL    | auto_increment |
| name          | varchar(255)    | NO   |     | NULL    |                |
| regulation_id | int(4) unsigned | NO   | MUL | NULL    |                |
| label         | varchar(255)    | NO   |     | NULL    |                |
+---------------+-----------------+------+-----+---------+----------------+
4 rows in set (0.03 sec)

mysql> describe filters;
+----------+----------------------+------+-----+---------+----------------+
| Field    | Type                 | Null | Key | Default | Extra          |
+----------+----------------------+------+-----+---------+----------------+
| id       | smallint(5) unsigned | NO   | PRI | NULL    | auto_increment |
| name     | varchar(100)         | NO   |     | NULL    |                |
| label    | text                 | NO   |     | NULL    |                |
| group_id | int(4) unsigned      | NO   | MUL | NULL    |                |
+----------+----------------------+------+-----+---------+----------------+

因此,当我烘焙应用程序时,我得到了以下Table类关系。全部都在initialize()方法内:

// RegulationsTable.php
$this->hasMany('Groups', [
        'foreignKey' => 'regulation_id'
    ]);

// GroupsTable.php
$this->belongsTo('Regulations', [
        'foreignKey' => 'regulation_id',
        'joinType' => 'INNER'
    ]);
    $this->hasMany('Filters', [
        'foreignKey' => 'group_id'
    ]);

 // FiltersTable.php
 $this->belongsTo('Groups', [
        'foreignKey' => 'group_id',
        'joinType' => 'INNER'
    ]);

在我看来,这似乎是正确的,因为就架构而言,这些都是关系。

但是,当我尝试在Controller中执行此操作时:

$regulations = TableRegistry::getTableLocator()->get('Regulations');
$data = $regulations->find('all')->contain(['Groups', 'Filters']);
$data = $data->toArray();
debug($data);

出现错误:

  

“法规”中未定义“过滤器”关联。

很明显。因为通过组(GroupsTable.php)模型来处理该关联。过滤器和法规之间没有直接关系;它必须通过网上论坛。

请有人能告诉我烘焙模型出了什么问题,以免产生错误吗?

有关背景信息:用例正在以分层格式(规则->组->过滤器)获取数据列表(特别是每个表中的label)。

0 个答案:

没有答案