You probably wouldn't be using a relationships.ini file for this. I'd be looking more towards grafted fields and possibly overriding the xxx__display() method for the grafted field. The basic implementation is simple, however the thing that makes it a little more complex is the fact that you probably don't want to be performing this calculation for every row in every request - so you'll probably want to have some sort of caching strategy.
Here's one such strategy:
1. Create a table called company_stats with columns (company_id, and num_sites)
This table is meant to simply cache calculated data. (of course you could skip this and just add a field called num_sites directly to the company table, but some might not be comfortable mixing columns that are actually part of the company entity with columns that are simply meant to cache statistics).
2. Using the __sql__ directive in the company table, we graft the company_stats table onto it:
- Code: Select all
__sql__ = "select c.*, s.num_sites from company c left join company_stats s on c.company_id=s.company_id"
3. Refresh the company_stats table whenever the SiteData table is modified. You could do this simply in an afterSave() trigger on the SiteData table, but this would only be called if updates are made through Xataface... We're going to actually compare the table modification times in the beforeHandleRequest() method and update the company_stats table if the SiteData modification time is newer than the company_stats table (**caveat*** this only works if you are using MYISAM for your table type... INNODB doesn't make modification times available to you).
- Code: Select all
function beforeHandleRequest(){
$modification_times = Dataface_Table::getTableModificationTimes();
if ( $modification_times['company_stats'] < $modification_times['SiteData'] ){
$res = mysql_query("replace into company_stats (company_id, num_sites) select company_id, count(*) as num_sites from SiteData group by company_id", df_db());
if ( !$res ) throw new Exception(mysql_error(df_db()));
}
}