Composite keys

You've also already come across compound keys a bit in the chapter on definitions. The term compound keys means the same thing as in SQL. That is, they are keys created over multiple columns - in this case, multiple entity properties.

There is a situation where the composite key is defined automatically, and by definition. If an entity has multiple properties marked as property IDs, then these properties automatically become the primary composite key. Let's illustrate such a situation and again reach for a piece of sample application. Specifically, recall the sample class JetApplication\Content_Article_Localized representing a localized version of an article. This has two properties marked as identifying:

#[DataModel_Definition(
    
typeDataModel::TYPE_ID,
    
is_idtrue//*** !!! ***
    
related_to'main.id',
    
do_not_exporttrue
)]
protected 
string|null $article_id '';

#[
DataModel_Definition(
    
typeDataModel::TYPE_LOCALE,
    
is_idtrue//*** !!! ***
    
do_not_exporttrue
)]
protected 
Locale|null $locale;

And if you look at how the database table is created, you will find the primary key above these two columns. This is the most common situation in practice when you are operating with compound keys and there is nothing else to do for the definition.

Well yeah, but what if for some reason we need to create a composite key over properties that are not marked as identifying? And what if we also need such a key to be not primary (after all, it is reserved just for record identification), but perhaps unique, or on the contrary a regular index? The solution is to define an extra key. Of course, you can "click" it within Jet Studio, but let's see how the definition of such a compound key looks like, which is part of the class attributes:

namespace JetApplicationModule\Test\ORM;

use 
Jet\DataModel;
use 
Jet\DataModel_Definition;
use 
Jet\DataModel_Query;
use 
Jet\DataModel_IDController_UniqueString;

#[
DataModel_Definition(
    
name'model_c1',
    
database_table_name'model_c1',
    
id_controller_classDataModel_IDController_UniqueString::class,
    
id_controller_options: [
        
'id_property_name' => 'id'
    
],
    
key: [
        
'name' => 'my_key',
        
'property_names' => [
            
'id',
            
'text'
        
],
        
'type' => DataModel::KEY_TYPE_INDEX
    
]
)]
class 
Model_C1 extends DataModel
{
    
//... ... ...   
}

Thus, the definition of a compound key is part of the class definition, and there can be more than one compound key defined in this way - not just one, as shown in the example.

The definition consists of the following parts:

  • name
    Name of the compound key.
  • property_names
    The names of the properties that make up the key.
  • type
    Key type.
The key type can be:
  • DataModel::KEY_TYPE_PRIMARY
  • DataModel::KEY_TYPE_UNIQUE
  • DataModel::KEY_TYPE_INDEX

Previous chapter
External relation
Next chapter
Events