Love Fuel?    Donate

FuelPHP Forums

Ask your question about FuelPHP in the appropriate forum, or help others by answering their questions.
Counting Lazy-Loaded One-To-Many Relationship Entities
  • Hi, Let's say I have an article who has a one-to-many relationship with comments. I have fetched my article entities without eager-loading the related comments. Now, I'd like to simply get a count of all the related comments. Is this possible with the ORM or will I need to build a query? Something like: <code>var_dump($objArticle->comments->count());</code> I know that when you access the property comments that it actually returns an array of comment entities so this obviously will not work as written. I'm just wondering if there is a correct way of doing this without manually writing a separate query?
  • I would like to know the answer to this a well... I'm new to FUELphp .. and I love it.
  • No, you can't. If you don't use eager loading, nothing is loaded, so there's nothing to count. To count, you need to load them (which is a query) or run a count query (is a query too). You can switch to eager loading, which also is a query. In the end, no matter what you do, you'll have to access the database to get the result count...
  • Thanks WanWizard. My thought was that the ORM might execute a SELECT COUNT(*) FROM foo type query rather than having to actually fetch all the entity data. It would be helpful for those cases where I simply want to count how many related entities there are, but am not interested in the details. "or run a count query" I must have missed this in the documentation if it's possible, but this is exactly what I'm looking for. I know I can do this with the DB class, but is it possible with the ORM? Thanks!
  • count() does run a count query, but currently it works for the main table only, not for related tables.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

In this Discussion