Basics
The schema of the database is declared in Data Object in the code. Those objects will be referred to as Entities
. Retrieving (querying) and persisting entities is done using the Swift\Orm\EntityManager
.
#
Create, update, and deleteAll persistence actions are done using the Swift\Orm\EntityManager
.
#
CreateTo create a new record of an entity, create a new class instance and add the values. After that persist the entity and run entity Manager.
In order to prevent the system from breaking, you might want to catch errors.
#
UpdateTo be able to update an object, you must first query the object.
By default the ORM will only update the fields that have changed. The given code would product SQL code like this:
#
Delete an entityAn entity can be deleted by calling the delete
method on the EntityManager.
Please note, the ORM will not automatically trigger the delete operation for related entities and will rely on foreign key rules set in the database.
#
Direct database queriesYou can always talk to the database directly without using the ORM abstraction on top of it. You can do this by injecting the Swift\Dbal\Dbal
service. This is a direct implementation of the Cycle\Database\DatabaseInterface
.
#
Selecting dataThe most common way to select data from the database is using the Swift\Orm\EntityManager
. To use the entity manager you need to inject the Swift\Orm\EntityManager
service.
The Entity Manager provides multiple methods to select the entity.
To find the entity using its primary key:
Null will be returned if the entity was not found.
You can use default values in the query. Field names will automatically be converted to the correct database field name.
More advanced queries can be created using the Swift\Dbal\Arguments\Arguments
. Custom Arguments can easily be used to create custom queries. An argument is a class implementing the Swift\Dbal\Arguments\ArgumentInterface
.
The method findMany
will return an Swift\Orm\Dbal\ResultCollectionInterface
, which is an Iterator with some handy additional methods to aid in e.g. pagination.
#
Simple relationA significant part of the ORM is the ability to handle relations between objects. Relations are defined in the entity definition class using attributes.
#
Describe the entityFirstly we will have to create two entities we want to relate to one another. The first entity is called Movie
and the second entity is called Actor
.
And the entity we want to define a relationship with.
To relate our entities we have to add a new property to one of them and annotate it properly. We should also add getter and setter for this property.
We can also refer to the other side of the relation. Because we already defined the relationship in the other entity we just read it, as it's already defined in this side of the relation automatically.
#
Persisting related entitiesEntities can have relations, embedded entities, and collections. Those are all handled by the ORM.