XF 2.2 Fetch some entity entries: finder, canView() etc


Active member
I have my own Entity for something.
This entity has the column allow_usergroups which have type SERIALIZED_ARRAY and includes some user group ids and [-1] for all.

Now I want to use the Finder to display some latest entries if the visitor belongs to that allow_usergroups array.

How I could achieve it?

I tried:
                            ['allow_usergroups', \XF::visitor()->user_group_id],
                            ['allow_usergroups', \XF::visitor()->secondary_group_ids]
But with no result.

I have also a canView method on my Entity but it seems it has no connectivity with the finder.

I could fetch() some entity entries and then to use !$entry->canView() for unsetting, but it kills the limit() of the final list. :(


XenForo developer
Staff member
When you write a where condition in a finder, it's generally fairly naive. So the code you demonstrated is basically just WHERE allow_usergroups = <user_group_id> OR allow_usergroups IN (<comma list of secondary group ids>). But if you're storing this as a serialized array, these will never match. You would need to manually build up query conditions to do LIKE-based matches on your serialized data (as encoded as a string).

We don't generally recommend using serialized encoding unless you have a specific need to (you want to store a PHP object directly). SERIALIZED_ARRAY is specifically marked as deprecated, pointing to JSON_ARRAY. That doesn't entirely solve your issue but it does make the data storage lighter and potentially easier to work with. Saying that, if you're storing a list of user group IDs, look at how we store the allowed group IDs for prefixes: a comma delimited list. That would be stored as 1,2,3,4 for example. When stored like this, you can build a query based on MySQL's FIND_IN_SET method to more easily search that field (though the query may still be a bit awkward to search).

Of course, the other option is to store these relationships in a separate table (like how we store the forum<->thread prefix relationship) and query them in joins.

I have also a canView method on my Entity but it seems it has no connectivity with the finder.
No, it doesn't. This is just arbitrary PHP (and very often includes code that can't reasonably be implemented in SQL).

You may need to investigate how to implement your viewing constraints into SQL. This might involve things like limiting sections (like nodes) or by content visibility (discussion_state/message_state). In terms of official code, XFMG has the most complex logic here because it handles both categories and personal albums which have individual privacy controls, which we use on the SQL side to know what is visible. But the more complex logic here, the lower performance may be.