Silverstripe 3 Tables (1 Linking Table) ORM 实现

Silverstripe 3 Tables (1 Linking Table) ORM implementaton

我得到了三个数据库tables

Table 名称列 1 id1,column1 2 id2,column2 3 id1, id2 (来自 tables 1 and 2)

所以如果 table 1 有 column1 行,

row 1 = a 
row 2 = b 
row 3 = c 

和table 2有列2行

第 4 行 = d 第 5 行 = e

那么如果 table 3 有行

1 4   = a, d columns
1 5   = a, e columns
3 4   = c, d columns
1 5   = a, e columns

这意味着Table 3的pk1和pk2将分别从Tables 1和2得到column1和column2。

问题是如何使用 Silverstripe 的 ORM 实现它?

您不需要为 SilverStripe 中的多对多关系创建联结 table。这太酷了。您可以在一侧使用 $many_many 并在另一侧使用 $belongs_many_many 来定义 class 关系。如果您需要在连接点 table 中添加一些自定义字段(例如,用于自定义排序),您可以定义 $many_many_extraFields

所以一个例子可能是这样的:

class Student extends DataObject {
    private static $db = array(//your stuff here);
    private static $many_many = array(
        'Classes' => 'SchoolClass' // naming it "Class" won't work...
    );
    private static $many_many_extraFields = array(
        'SortOrder => 'Int'
    );
/* .... */
}

class SchoolClass extends DataObject {
    private static $db = array(//your stuff here);
    private static $belongs_many_many = array(
        'Students' => 'Student' 
    );

/* .... */
}

另请参阅: