1

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->matrixField->textField($stringToMatch)->first();

$relatedEntries = $matrixRow->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()->elements->getCriteria(ElementType::Entry);
$criteria->section         = 'videos';
$criteria->relatedTo       = array(
    'targetElement'   => $matrixRow,
    'field'     => 'relationshipField'
);

$entries = $criteria->find();

foreach($entries as $entry){
    var_dump($entry->title);
}
2

$matrixRow->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->relationshipField->order('RAND()')->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.

| improve this answer | |
  • I have just discovered this and came here to edit my question. Brilliant! Makes life much easier! – foamcow Dec 5 '17 at 16:07
1

The ElementCriteriaModel has a function nth($offset) link so you could get a random number between 0 and count() and put it in your nth() function

$randomNumber = rand(0, $matrixRow->relationshipField->count());
$relatedEntry = $matrixRow->relationshipField->nth($randomNumber);

As an answer to your edit: you know that $matrixRow->relationshipField is nearly the same as your edit? $matrixRow->relationshipField is an object, it is not an array of elements. It has an iterable interface so the $criteria->find() method is executed as soon as you loop through it. So in the end the criteria you build is nearly the same object like Craft gives you with $matrixRow->relationshipField

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.