I have a User and Address entity. A user can have many Addresses, but only one of them can be marked as active
.
I want the User entity to have a property that is $activeAddress which would contain an Address. In other words, getActiveAddress() would return an Address object.
Is there a way to set up an annotation to do this similar to a one to one annotation? This is essentially a one to one relationship as long as we are able to enforce a filter.
So for User with an id of 5:
SELECT * FROM address WHERE active = 1 AND user_id = 5 LIMIT 1;
This would always return the active address. How do I set up my User entity to reflect this?
You could use the collection criteria API which allows you to transparently filter collections. Doctrine will trigger either a SQL query or filter the in memory association when it is already loaded.
public function getActiveAddress()
{
$criteria = Criteria::create()
->where(Criteria::expr()->eq("active", true))
->setMaxResults(1);
$addresses = $this->addresses->matching($criteria);
if ($addresses->count() == 1) {
return $addresses->current();
}
return null;
}