Skip to content

Instantly share code, notes, and snippets.

@philipboomy
Forked from Anubarak/OrderByRelatedTo.php
Created April 4, 2019 16:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save philipboomy/c33247ad6c643551fb3e537ad56dd029 to your computer and use it in GitHub Desktop.
Save philipboomy/c33247ad6c643551fb3e537ad56dd029 to your computer and use it in GitHub Desktop.
<?php
// Element API endpoint
'news.json' => function() {
return [
'elementType' => Entry::class,
'criteria' => [
'section' => 'news'
'join' => [
[
'LEFT JOIN',
'{{%relations}} as myrelations',
'[[myrelations.sourceId]] = [[elements.id]] AND [[myrelations.fieldId]] = 9'
],
[
'LEFT JOIN',
'{{%content}} as mycontent',
'[[mycontent.elementId]] = [[myrelations.targetId]]'
]
],
'orderBy' => 'mycontent.title desc'
],
];
},
// TWIG
{% set fieldId = 9 %}
{% set entries = craft
.entries
.section('awesomeNews')
.leftJoin('{{%relations}} as myrelations', '[[myrelations.sourceId]] = [[elements.id]] and [[myrelations.fieldId]] = ' ~ fieldId)
.leftJoin('{{%content}} as mycontent', '[[myrelations.targetId]] = [[mycontent.elementId]]')
.groupBy('elements.id')
.orderBy({'mycontent.title': SORT_ASC})
.all()
%}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment