Jump to content

Using numReferences in selectors?


schwarzdesign
 Share

Recommended Posts

ProcessWire added the numReferences property in 3.0.107, which returns the count of all pages having a reference to the page object. However, apparently it's not possible to use this property inside a selector. I'm trying to find all pages that are referenced at least once:

$pages->find('template=service, numReferences>0');

This throws an error: "Field does not exist: numReferences".

Is there another way to filter by the number of references? Of course, I could manually filter the results of the find query, but that feels overly complicated. Ideally, I would also like to filter the number of references from a specific field; that is, find all pages that are referenced at least once in one specific page reference field.

Is there a way to do this? I guess supporting numReferences in selectors would be a feature request - if so, is it feasible?

Thanks!

 

Link to comment
Share on other sites

6 hours ago, schwarzdesign said:

However, apparently it's not possible to use this property inside a selector.

That's because ultimately the references depend on the execution of the FieldtypePage::findReferences() method. This method has to be called for each page you want to get or count the references to. And so the number of references is not a simple value in the database that you can query in a $pages->find() selector the way a field value is.

Enabling selectors that query or sort by the number of references is one of the motivations behind the Connect Page Fields module. If you use this module to create a two-way relationship between Page Reference fields then it's easy to write the selector you want. Note that you can set the visibility of a Page Reference field to hidden if you don't need to see it in Page Edit but only want to query it in selectors.

  • Like 5
Link to comment
Share on other sites

@dragan Referenced to the page that is being searched. I think Robin's explanation is pretty accurate. For example, I have five service pages, but only three of them are referenced from different pages (in a page reference field). I want to write a query that will retrieve those three services; the problem here is that numReferences is not a real field, but a computed property.

@Robin S Thanks for the explanation! That's what I assumed - I guess it would be possible with a subquery, but I agree that the incurred performance hit would make it a bad tradeoff for selectors. Your module looks ingenious, I'll try it out for my usecase!

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...