Stand With Ukraine. Stop Putin. Stop War.

Sometimes you need to define multiple criteria in xPDO schemas to make sure your relations are properly defined. I came across this while working on a project that needed some existing databases integrated. This specific case had one "fl_translations" table that contained the translations for thousands of objects. To get the translations for a specific object, you would need to filter that table on the "originaltable" field. For example, one row might have originaltable=fl_colors and contains the translation for the color in a specific language.

In order to properly define this relation, I went browsing the MODX core schema for some ideas, and I stumbled across a pretty much undocumented feature of xPDO Schemas: relation criteria!

Here's a snippet of the final schema:

<object class="flColor" table="fl_colors" extends="xPDOSimpleObject">
	<!-- .. some fields .. -->
	<composite alias="Translations" class="flTranslation" local="id" foreign="thekey" owner="local" cardinality="many">
		<criteria target="foreign"><![CDATA[
<object class="flTranslation" table="fl_translations" extends="xPDOSimpleObject">
	<field key="originaltable" dbtype="varchar" precision="50" phptype="string" null="true" />
	<!-- .. some more fields .. -->

Basically, while with a normal relation you would immediately close the <composite> (or <aggregate>) element, but if you want additional filters (criteria) on the relation, you can define that. A simple <criteria> object with a target (I presume but haven't tested that you can add an additional <criteria> object with a target of local), and inside it a JSON object with the fieldname (of the foreign object) and the value it should have (in this case, fl_colors, as that's how it was set up).

This way of defining relations is very powerful and I imagine some really complicated relations could be defined once (in the schema) and reused without knowing all the details by simply calling getMany('RelationAlias').

The core uses this type of relationship for defining the PropertySets relations on elements and also in the modAccess definition. For example, here is a snippet from the core schema for modChunk:

<composite alias="PropertySets" class="modElementPropertySet" local="id" foreign="element" owner="local" cardinality="many">
     <criteria target="foreign"><![CDATA[

xPDO is quite nifty eh?

Get the conversation going, and post your thoughts in a reply.

Comments are closed :(

While I would prefer to keep comments open indefinitely, the amount of spam that old articles attract is becoming a strain to keep up with and I can't always answer questions about ancient blog postings. If you have valuable feedback or important questions, please feel free to get in touch.