I have a doctrine entity called Site with the following field:
/**
* @ORM\OneToMany(targetEntity="SiteAsset", mappedBy="site")
*/
protected $assets;
I also have a function for getting an element of $assets
with a given value of its url
field:
public function getAssetByUrl($url) {
$c = Criteria::create()->
where(Criteria::expr()->eq('url',$url));
$matching = $this->assets->matching($c);
return $matching[0];
}
This function behaves very strangely. It appears to work if I run it immediately after fetching the entity from the database. But after a few database operations have been queued up, it begins to fail. I know it is failing, as I can find the asset I want as follows:
public function getAssetByUrl($url) {
foreach($this->assets as $asset) {
if($asset->getUrl() === $url) {
return $asset;
}
}
}
Furthermore, if I combine the two functions into:
public function getAssetByUrl($url) {
foreach($this->assets as $asset) {
if($asset->getUrl() === $url) {
error_log('found');
}
}
$c = Criteria::create()->
where(Criteria::expr()->eq('url',$url));
$matching = $this->assets->matching($c);
error_log($matching[0] ? 'found' : 'not found');
return $matching[0];
}
Then the Criteria always fails to find a match (i.e., when the function is called it always prints out 'found' followed by 'not found'). This would suggest that Doctrine is failing to find the entity I want in the case when it has already cached the entities in memory.
How can I ensure that matches are always found, while still making use of Doctrine's Criteria filtering system?