CakePHP 3.0使用belongsTo连接到嵌套表

时间:2015-12-11 23:04:10

标签: sql-server cakephp join cakephp-3.0

上下文

我在CakePHP 3.0中进行了一些有点复杂的嵌套连接:

$query = $this->find()
    ->contain([
        'A',
        'A.B',
        'A.B.C',
        'A.B.C.D',
        'A.B.C.D.Z'
    ]);

ABCDZ之间的关系如下:

  • B hasMany A
  • B hasMany C
  • C hasMany B
  • C hasMany D
  • D hasMany C
  • Z hasMany D

contain()数组中,我可以AA.BA.B.CA.B.C.D,但 { {1}}。给出的错误消息是:

A.B.C.D.Z

我没有找到D is not associated with Z (InvalidArgumentException) Could this be caused by using AutoTables? Please try correcting the issue for the following table aliases: • D 的任何拼写错误的引用。

问题:

如何在此加入声明中包含D

代码:

我的Z型号:

C

我的<?php namespace App\Model\Table; use Cake\ORM\Table; class CTable extends Table { public function initialize(array $config) { $this->table('c'); $this->primaryKey('id'); $this->hasMany('D', [ 'className' => 'D', 'foreignKey' => false, 'conditions' => ['D.id' => 'C.d_id'] ]); $this->hasMany('B', [ 'className' => 'B', 'foreignKey' => false, 'conditions' => ['B.id' => 'C.b_id'] ]); } } 型号:

D

我的<?php namespace App\Model\Table use Cake\ORM\Table; class DTable extends Table { public function initialize(array $config) { $this->table('z'); $this->primaryKey('id'); $this->hasMany('C', [ 'className' => 'C', 'foreignKey' => 'd_id' ]); $this->belongsTo('Z', [ 'className' => 'Z', 'foreignKey' => 'z_id' ]); } } 型号:

Z

数据库:

我的<?php namespace App\Model\Table; use Cake\ORM\Table; class ZTable extends Table { public function initialize(array $config) { $this->table('z'); $this->primaryKey('id'); $this->hasMany('D', [ 'className' => 'D', 'foreignKey' => 'z_id' ]); // Unrelated to the join statement, but in here nevertheless $this->belongsTo('X', [ 'className' => 'X', 'foreignKey' => 'x_id', ]); } } 表格列:

C

我的id | b_id | d_id 表格列:

D

我的id | z_id | data 表格列:

Z

2 个答案:

答案 0 :(得分:0)

您的文件需要分别命名为DTable.php CTable.php和类class DTable extends Table

答案 1 :(得分:0)

据我所知,问题是通过“hasMany”关系在 C 和 D 之间进行递归。 也许将这种关系在 C 中重命名如下:

$this->hasMany('aliasForD', [
        'className' => 'D',
        'foreignKey' => false,
        'conditions' => ['aliasForD.id' => 'C.d_id']
]);