Getting a single, random, related entry within a plug in Given a Matrix with each row containing a text field and a multi relationship field. And I am picking 1 Matrix row based on the value in the text field. How would I go about selecting a single, random, related entry for that row?

I've tried to do this a couple of ways but I'm not really getting anywhere.

I'm selecting the Matrix row and getting the related entries using

$matrixRow = $entry-&gt;matrixField-&gt;textField($stringToMatch)-&gt;first();

$relatedEntries = $matrixRow-&gt;relationshipField;


But how can I now pick one of those related entries at random?
Is the only way to create an array and shuffle it?
Or is there a way I can do it when fetching the Matrix row?

I've tried adding the following in an attempt to get all the related entries associated with the Matrix row. Figuring I can then modify this query by adding a limit and ordering randomly to get my 1 related entry. But it's coming back empty.

$criteria = craft()-&gt;elements-&gt;getCriteria(ElementType::Entry);
$criteria-&gt;section         = 'videos';
$criteria-&gt;relatedTo       = array(
    'targetElement'   =&gt; $matrixRow,
    'field'     =&gt; 'relationshipField'
);

$entries = $criteria-&gt;find();

foreach($entries as $entry){
    var_dump($entry-&gt;title);
}
$matrixRow-&gt;relationshipField returns an ElementCriteriaModel pre-configured to query for the related elements. You can add / override additional criteria and then query for a matching element using the first() method.

$randomEntry = $matrixRow-&gt;relationshipField-&gt;order('RAND()')-&gt;first();


This is basically the same as what you’ve tried with your custom ElementCriteriaModel. It should also work once you have fixed the mistake in the relatedTo param, as the entry that holds the field is the “sourceElement” of a relation.