简体   繁体   English

CakePHP 2复合主键

[英]CakePHP 2 Composite Primary Key

Lets say I have a table called positions where i save the coordinates of every computer, monitor or printer. 假设我有一个名为position的表,我保存每台计算机,显示器或打印机的坐标。

+-----------------+
| key | type | id |
+-----------------+
| 1   | PC   | 1  |
| 2   | PC   | 2  |
| 3   | MO   | 1  |
+-----------------+

In this scenario, type and id are the primary keys. 在这种情况下,type和id是主键。 I read Cake doesn't support composite primary keys and suggests to use direct querys for that. 我读过Cake不支持复合主键,并建议使用直接查询。 Is there really no workaround for that? 那真的没有解决方法吗? Is it better to save the coordinates for PCs directly in the PC table or in a table especially for PC positions? 将PC的坐标直接保存在PC表或表格中,尤其是PC位置是否更好? That's hard to swallow. 这很难吞下去。

Not supported until version 3 直到版本3才支持

Composite primary keys aren't supported until CakePHP version 3. CakePHP版本3之前不支持复合主键

You can make composite primary keys work, but it's not trivial to do so (in summary, treat/nominate one of the fields as the primaryKey and handle the other with callbacks; need to overwrite Model::exists , add conditions to any associations) - if it's possible to do so it's easier to add an unique key to the table - that will permit normal usage and all-round "it just works"-ness. 可以使复合主键工作,但这样做并不简单(总之,将其中一个字段作为primaryKey处理/指定,并使用回调处理另​​一个;需要覆盖Model :: exists ,为任何关联添加条件) - 如果可以这样做,那么更容易为表添加一个唯一的密钥 - 这将允许正常使用和全面“它只是工作” - 性。

That's a polymorphic association 这是一种多态关联

Know that what you've got in the question is a polymorphic association (Position belongsTo PC, Position belongsTo MO), while you could treat those two fields as the primary key they are really expressing the association - this behavior may be useful to you, it also contains examples of defining model associations using conditions which are possibly relevant to your use case. 知道你在问题中得到的是多态关联(位置属于PC,位置属于MO),而你可以将这两个字段视为他们真正表达关联的主键 - 这种行为可能对你有用,它还包含使用可能与您的用例相关的条件定义模型关联的示例。

For example based on the info in the question this schema will make usage easier: 例如,基于问题中的信息,此架构将使用法更容易:

CREATE TABLE `positions` ( 
  `id` int(11) unsigned NOT NULL auto_increment, // <- added
  `type` varchar(30) NOT NULL, 
  `foreign_id` int(11) unsigned NOT NULL, // <- called "id" in the question
  `key` int(11) unsigned NOT NULL,
  PRIMARY KEY  (`id`),
  KEY  (`foreign_id`, `type`)
);

And this would be an example of the inverse model association: 这将是逆模型关联的一个例子:

class Pc extends AppModel { 

    public $hasOne = array( 
        'Position' => array( 
            'foreignKey' => 'foreign_id',
            'conditions' => array('Position.type' => 'PC'), 
            'dependent' => true 
        ) 
    ); 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM