如果您希望 1 名玩家 (TeamMember) 在多个团队中,并且团队中有多个玩家,您需要一个 many_many。如果在这里使用 has_many,那么 Team 将有一个 PlayerID,这意味着每个团队中只能有 1 个 Player。
class TeamPage extends Page {
private static $many_many = array('TeamMembers' => 'TeamMember');
public function getCMSFields() {
$fields = parent::getCMSFields();
$fields->addFieldToTab('Root', Tab::create('MembersTab', 'Team Members'));
$fields->addFieldToTab('Root.MembersTab', GridField::create('TeamMembers', 'The Team Members', $this->TeamMembers(), GridFieldConfig_RelationEditor::create());
return $fields;
}
}
class TeamMember extends DataObject {
private static $belongs_many_many = array('Teams' => 'TeamPage');
public function getCMSFields() {
$fields = FieldList::create();
if (!$this->isInDB()) {
// if the TeamMember has not been saved yet, display a message that it needs to be saved before teams can be assigned
$fields->push(ReadOnlyField::create('Teams', '', 'Save to assign Teams'));
} else {
$config = GridFieldConfig_RelationEditor::create();
// if you don't want the "add a new team" button on this grid, you can remove that with the following line:
// $config->removeComponentsByType('GridFieldAddNewButton');
$fields->push(GridField::create('Teams', 'Team this Member is in', $this->Teams(), $config);
}
return $fields;
}
}
请注意,我使用GridFieldConfig_RelationEditor
的不是GridFieldConfig_RecordEditor
它,而是向您的网格字段添加一个GridFieldAddExistingAutocompleter
允许您链接对象的。