CakePHP 2复合主键

FRu*_*les 5 mysql sql cakephp

假设我有一个名为position的表,我保存每台计算机,显示器或打印机的坐标.

+-----------------+
| key | type | id |
+-----------------+
| 1   | PC   | 1  |
| 2   | PC   | 2  |
| 3   | MO   | 1  |
+-----------------+
Run Code Online (Sandbox Code Playgroud)

在这种情况下,type和id是主键.我读过Cake不支持复合主键,并建议使用直接查询.那真的没有解决方法吗?将PC的坐标直接保存在PC表或表格中,尤其是PC位置是否更好?这很难吞下去.

AD7*_*six 4

版本 3 之前不支持

CakePHP 版本 3 之前不支持复合主键。

可以使复合主键起作用,但这样做并不简单(总之,将其中一个字段视为 PrimaryKey 并使用回调处理另​​一个字段;需要覆盖Model::exists,向任何关联添加条件) - 如果可以的话,向表中添加唯一键会更容易 - 这将允许正常使用和全面的“它就可以工作”。

这是一个多态关联

知道你在问题中得到的是多态关联(位置属于 PC,位置属于 MO),虽然你可以将这两个字段视为主键,但它们实际上表达了关联 -这种行为可能对你有用,它还包含使用可能与您的用例相关的条件定义模型关联的示例。

例如,根据问题中的信息,此架构将使使用更容易:

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`)
);
Run Code Online (Sandbox Code Playgroud)

这是逆模型关联的一个例子:

class Pc extends AppModel { 

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