How to define composite primary key in SilverStripe ORM/Dataobject

Deadly 提交于 2019-12-10 20:25:28

问题


SilverStripe's DataObject gives us the following to start with:

ID - primary key

But how do you define a composite key (primary key composed of 2 or more columns)? I've searched the documentation and can not find this information anywhere.


回答1:


I'm not sure about the primary key, but you can set a unique index instead. It should give you a sort-a-like result as mentioned here.

class YourDataObject extends DataObject
{
    private static $db = [
        'MyField' => 'Varchar',
        'MyOtherField' => 'Varchar'
    ];

    private static $indexes = array(
        'MyIndexName' => array(
            'type' => 'unique', // changed this to unique
            'value' => '"MyField","MyOtherField"'
        )
    );
}

With this code, it is not possible to create a YourDataObject with MyField = 'test' and MyOtherField = 'othertest' if a there already is a record with BOTH those values in the database. It is possible to create a YourDataObject with only the MyField as test and MyOtherField as something else.

However, it is recommended to check on this before you write it to your database, as you would get a user-unfriedly error in your ModelAdmin.

Code copied from the documentation



来源:https://stackoverflow.com/questions/37325001/how-to-define-composite-primary-key-in-silverstripe-orm-dataobject

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!