I stumbled today over the question how to filter associations. And just in case you are like me and didn’t read the awesome paragraph in the documentation about it, here is the difference between addAssociation
and getAssociation
in quick:
public function addAssociation(string $path): self { $parts = explode('.', $path); $criteria = $this; foreach ($parts as $part) { if (mb_strtolower($part) === 'extensions') { continue; } $criteria = $criteria->getAssociation($part); } return $this; }
public function getAssociation(string $path): Criteria { $parts = explode('.', $path); $criteria = $this; foreach ($parts as $part) { if ($part === 'extensions') { continue; } if (!$criteria->hasAssociation($part)) { $criteria->associations[$part] = new Criteria(); } $criteria = $criteria->associations[$part]; } return $criteria; }
The important part is return $this
vs return $criteria
. getAssociation()
runs down the associations and returns the Criteria for the association, while addAssociation doing the same, except it does NOT return the found criteria, but only adds a new association to it.
And if you are wondering, what you can do with it: EVERYTHING!
You can:
- filter
- sort
- addAssocations
- addAggregations
- limits
- etc.
One thought on “addAssociation() vs getAssociation()”