Session: How to Evict Single Entity from a Session
We can clear all session operations and stop tracking of all entities using the
clear method, but sometimes
there's a need to do cleanup only for one entity. This is what evict
is for.
Syntax
public function evict(object $entity): void;
Parameter | Type | Description |
---|---|---|
$entity | object |
Instance of an entity that will be evicted |
Example I
$employee1 = new Employee();
$employee1->setFirstName("John");
$employee1->setLastName("Doe");
$employee2 = new Employee();
$employee2->setFirstName("Joe");
$employee2->setLastName("Shmoe");
$session->store($employee1);
$session->store($employee2);
$session->advanced()->evict($employee1);
$session->saveChanges(); // only 'Joe Shmoe' will be saved
Example II
$employee = $session->load(Employee::class, "employees/1-A");//loading from serer
$employee = $session->load(Employee::class, "employees/1-A"); // no server call
$session->advanced()->evict($employee);
$employee = $session->load(Employee::class, "employees/1-A"); // loading form server