Here is a simple example of using the ORM (Object-Relational Mapper) in SilverStripe to create a data object, insert a record into the database, and retrieve the record:
use SilverStripe\ORM\DataObject;
use SilverStripe\Forms\FieldList;
use SilverStripe\Forms\TextField;
class Person extends DataObject
{
private static $db = [
'Name' => 'Varchar',
'Age' => 'Int',
];
public function getCMSFields()
{
return FieldList::create(
TextField::create('Name'),
TextField::create('Age')
);
}
}
// Insert a record into the database
$person = new Person();
$person->Name = 'John';
$person->Age = 30;
$person->write();
// Retrieve a record from the database
$person = Person::get()->filter(['Name' => 'John'])->first();
echo $person->Name; // Outputs "John"
echo $person->Age; // Outputs "30"
This example creates a Person
data object with two fields: Name
and Age
. The getCMSFields()
method is used to define the fields that will be displayed in the CMS when editing a person record.
The write()
method is used to insert a record into the database, and the filter()
and first()
methods are used to retrieve a record from the database.