Hi,
I’ve come across a weird query which i don’t really know how to wrap my head around doing only with a sql/active record query.
I have topics with custom fields, and i need to sort data using the value of ‘importedSortDate’ custom field.
Initial code
Topic.where(‘category_id in (?)’, [cat_id])
.where(‘closed = ?’, false)
.order(‘created_at desc’)
.limit(10)
How can I modify or add to this query so I load into memory only those 10 topics, and not more.
Since Custom Fields Table template is a bit weird, in the sense you have a name column and a value column, i’m a bit stuck on how exactly do i manage to do this all using the database query.
My issue with loading more in memory is the fact that for every topic i load into memory a category, user and post fetch are also performed.
I’m working with 1000-2000 topics per category, and i have 4 categories to fetch from.
The fetch is done by all users, it is not a one time thing.
As I see it I have 2 ways of doing it so far (first one doesn’t seem fast enough for me):
- Get only ids for all topics that i’m interested in 1 fetch and then use that info somehow join it with the value of ‘importedSortDate’ and then do a sort in memory and then again do a fetch for the ids in the same order i have them (again don’t really know exactly how that would work)
- somehow make a query that joins with the custom fields table (i’ve seen some examples but they were for fixed values on name and value columns) and sort this all based on the columns ‘name’ === ‘importedSortDate’ and the value column (iso8601 string)
How can I achieve this?
PS some topics may not have a value in the importedSortDate custom field, so I could just fetch those and put them wherever I want, but it’s an edge-case i can deal with. If they don’t have a value, they should be the first entries.
PPS I want to afterwards use this query as my pagination query, logic already implemented on that side, I just need to change the main query for fetching topics.