3

With v2 of the Element API plugin, I'm having issues with working out how to return entries that are in a particular category.

I've got the slug in the API route but can't work out what the query should be in the transformer.

Should I be doing this query in a total different way? I keep thinking I've just gone down the wrong way to do it completely.

'api/v1/category/<slug:{slug}>.json' => function($slug) {

        return [
            'elementType' => Entry::class,
            'elementsPerPage' => 30,
            'criteria' => [
              'section' => 'posts',
              'relatedTo' => ['targetElement' => ***category slug($slug)***],
            ],
            'transformer' => function(Entry $entry) {
                return [
                    'title' => $entry->title,
                    'id' => (int) $entry->id,
                    'slug' => $entry->slug,
                    'postDate' => $entry->postDate
                ];
            },
            'pretty' => true
        ];
    }

1 Answer 1

2

Your targetElement needs to be the category object or the ID of your category. So if the id of your category is 5 you need

'relatedTo' => ['targetElement' => 5],

If you really want to be able to fetch your category by slug (which I would not suggest since your slug can be changed in the cp but the ID can't, if someone changes the slug by accident your entire logic will break) you can create an ElementCriteriaModel to search for the category with the slug and insert the object there.

$criteria = craft()->elements->getCriteria(ElementType::Category);
$criteria->slug = $slug; 
$category = $criteria->find();

And inside your array

'relatedTo' => ['targetElement' => $category],
3
  • Targeting by ID definitely seems to make more sense now that you mention that, so that 'relatedTo' => ['targetElement' => 5], how does that know that it is a category its going to be relating to? actually, that ID is going to be unique - silly me
    – jamie
    Commented Feb 3, 2018 at 16:00
  • Works perfectly nice one Robin
    – jamie
    Commented Feb 3, 2018 at 16:05
  • 2
    Just to explain that: In Craft, there are elements (assets, users, categories, entries) every time you insert one of those 4 types a record in craft_elements is generated with some information about the record. When you insert an ID in the relatedTo it checks the record from craft_elements - in your case it will find a category in the type column - so it knows its a category and not an entry. That's the reason why you can relate everything with everything because there is one really huge table for all records Commented Feb 3, 2018 at 16:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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