I have a lot of trouble in understanding the database/model structure and how to work with the query builder. I tried playing a bit with leftJoins but i cannot seem to make complex queries in craft 3. I would like some help with a query.

The matrix field is as follows:

  • Entry
    • audienceTarget(matrix)
    • audience (block type)
      • targetName (field type: category)
      • points (field type: dropdown)

We use this to segment entries for certain users so we can show users that are segmented more relevant entries

Before i'm running the query i have the ids of the audience.targetName i want to favour in a variable let say $mainSegment.

What i am trying to do:

I want to query entries with the default order "postDate" but i like to place the relevant entries first. so all the entries that has the category id i specify must be first.

For example when a user is segmented on targetName(category) with id 2. I want to favour all the posts that has a block type with segment 2 selected on the matrix in my order by.

I could not find a lot of craft examples with complex queries so it would be very helpful if someone could give me some examples.

Thank you.

  • Is this Matrix on your users or on your entries?
    – Oli
    Feb 20, 2019 at 15:10
  • @OlivierBon On my entry. I edited my question to clarify it more. Thanks! Feb 20, 2019 at 16:02
  • It depends on how many entries you'll likely have, maybe it's easier to query for all matrixblocks that match the criteria and order those by their category. Then query for their owners. It adds an additional query and is less efficient but much easier to achieve and easier to maintain and extend. The problem is you need to join more than 5 tables and order queries differently between your sub query and main query. So you need to be familiar with Craft and it's internals. Here is how to order by related field gist.github.com/Anubarak/f610c1a1234b4f014046a7919ddbd142 Feb 20, 2019 at 19:18


Your Answer

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

Browse other questions tagged or ask your own question.