2015-10-06 50 views
1

我想在CakePHP 3.0中使用belongsToMany-through关联时设置使用的外键。指定在belongsToMany-through关联中的外键

考虑下面两个表:

实体:ID,标题
链接:ID,from_id,to_id,additional_information

我使用额外的,因为belongsToMany,通过协会我需要在直通表中存储信息。

下面是这两个表类:

class LinksTable extends AppTable 
{ 
    public function initialize(array $config) { 
     parent::initialize($config); 

     $this->belongsTo('FromEntities', [ 
      'className' => 'Entity', 
      'foreignKey' => 'from_id' 
     ]); 
     $this->belongsTo('ToEntities', [ 
      'className' => 'Entity', 
      'foreignKey' => 'to_id' 
     ]); 
    } 
} 

class EntitiesTable extends AppTable 
{ 
    public function initialize(array $config) { 
     parent::initialize($config); 

     $this->belongsToMany('Entities', [ 
      'through' => 'Links' 
     ]); 
    } 
} 

但当然CakePHP中试图加入表使用默认的外键entity_id,这是不正确的。

如何定义用于连接EntitiesTable类中的表的外键?

编辑:为了完整起见,在这里试图用$this->Entities->findById(1)->contain('Entities');协会获取实体时是错误信息和生成的查询。

Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Links.entity_id' in 'field list'

SELECT Links.entity_id AS `Links__entity_id`, Links.id AS `Links__id`, Links.from_id AS `Links__from_id`, Links.to_id AS `Links__to_id`, Links.type AS `Links__type`, Links.role AS `Links__role`, Entities.id AS `Entities__id`, Entities.type AS `Entities__type`, Entities.title AS `Entities__title`, Entities.user_id AS `Entities__user_id`, Entities.created AS `Entities__created` FROM entities Entities INNER JOIN links Links ON Entities.id = (Links.entity_id) WHERE Links.entity_id in (:c0) 

有在我剥离出来的代码示例上面,如果你想知道生成的查询一些附加字段。

回答

1

经过一些测试用例的挖掘,我找到了答案this test

belongsToMany有一个未公开的选项targetForeignKey,所以EntitiesTable类应该是这样的方法:

class EntitiesTable extends AppTable 
{ 
    public function initialize(array $config) { 
     parent::initialize($config); 

     $this->belongsToMany('LinkedEntities', [ 
      'className' => 'Entities', 
      'through' => 'Links', 
      'foreignKey' => 'from_id', 
      'targetForeignKey' => 'to_id' 
     ]); 
    } 
} 

现在我能够使用访问链接的实体$this->Entities->findById(1)->contain('LinkedEntities');