【问题标题】:Specifying the foreign keys in a belongsToMany-through association在 belongsToMany-through 关联中指定外键
【发布时间】:2015-10-06 08:32:12
【问题描述】:

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

考虑以下两个表:

实体:id、标题
链接:id、from_id、to_id、additional_information

我正在使用 belongsToMany-through 关联,因为我需要将其他信息存储在直通表中。

这是两个 Table 类:

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'); 获取具有关联的实体时的错误消息和生成的查询。

错误:SQLSTATE[42S22]:未找到列:1054 “字段列表”中的未知列“Links.entity_id”

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)

如果您想知道,我从上面的代码示例中删除了生成的查询中的一些附加字段。

【问题讨论】:

    标签: cakephp orm foreign-keys cakephp-3.0


    【解决方案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'); 访问链接实体

    【讨论】:

      猜你喜欢
      • 2011-01-06
      • 2015-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-03
      • 2017-08-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多