­
+1 (408) 320-0380

ORM: How to manage entities in your code

EspoCRM has built-in own ORM (Object-relational mapping). It’s very simple to create, update, read, delete and search entities. All these operations available through EntityManager object. EntityManager is available in record Services by method #getEntityManager().

$entityManager = $this->getEntityManager();

Create new entity

$account = $entityManager->getEntity('Account');

or

$account = $entityManager->getRepository('Account')->get();

Fetch existing entity

$account = $entityManager->getEntity('Account', $accountId);

or

$account = $entityManager->getRepository('Account')->get($accountId);

Store entity

$entityManager->saveEntity($account);

or

$entityManager->getRepository('Account')->save($account);

Remove entity

$entityManager->removeEntity($account);

or

$entityManager->getRepository('Account')->remove($account);

Find entities

1
2
3
$entityManager->getRepository('Account')->where(array(
    'type' => 'Customer',
))->find();

$entityManager->getRepository('Account')->limit(0, 10)->order('createdAt', 'DESC')->find();

Find first entity

1
2
3
$entityManager->getRepository('Account')->where(array(
    'type' => 'Customer',
))->findOne();

Find related entities

$entityManager->getRepository('Account')->findRelated($account, 'opportunities');

Relate two entities

$entityManager->getRepository('Account')->relate($account, 'opportunities', $opportunity);

or

$entityManager->getRepository('Account')->relate($account, 'opportunities', $opportunityId);

Remove relation

$entityManager->getRepository('Account')->unrelate($account, 'opportunities', $opportunity);

or

$entityManager->getRepository('Account')->unrelate($account, 'opportunities', $opportunityId);

Afterword

These are not all abilities of EntityManager. But in most cases they will be enough.

One comment on “ORM: How to manage entities in your code
  1. worldmiros says:

    What is the assigned field of $accountId?

Leave a Reply

Your email address will not be published. Required fields are marked *

*

Cookies & Privacy Policy

Our website uses cookies to give you the best user experience on our website and to help us deliver our services. By using our services, you agree to our use of cookies. Click here for more information.
Necessary
Strictly necessary cookies help make a website navigable by activating basic functions such as page navigation and access to secure website areas. Without these cookies, the website would not be able to work properly.
Statistical
Statistical cookies help the website owner understand how visitors interact with the website by collecting and reporting information.
Marketing
Marketing cookies are used to track visitors across websites. The intention is to display ads that are relevant and interesting to the individual user and thus more valuable for publishers and third-party advertisers.
Accept AllCustomizeAccept Necessary