3

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.

3dgoo
  • 15,716
  • 6
  • 46
  • 58
Learner One
  • 623
  • 5
  • 13

1 Answers1

2

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

Community
  • 1
  • 1
Fatal Error
  • 1,024
  • 6
  • 12