Hi All,
I have Three tables: companies, markets, and locations. A company has one or more markets and a market has one or more locations. I also have a configurations table. The companies, markets, and locations tables each has a nullable configuration_id field and Company, Market, and Location each have a hasOne() relationship to Configuration. (Configuration has a belongsTo() relationship to each of the three models.) The purpose is so that configuration settings can be defined at any of those three levels in an overriding fashion, with company being the default and location being the most granular. In other words, if a configuration_id is defined at the location level then that is used. Otherwise if locations.configuration_id is null and markets.configuration_id is populated then markets.configuration_id is used. Otherwise, companies.configuration_id is used.
I'm looking for the most elegant way to figure out which configuration record to use based on the company > market > location hierarchy. This can be accomplished in raw SQL (MySQL) like so:
SELECT IFNULL(locations.configuration_id,
IFNULL(markets.configuration_id,
companies.configuration_id
)
) AS configuration_id
FROM locations
JOIN markets ON markets.id = locations.market_id
JOIN companies ON companies.id = markets.company_id
WHERE locations.id = 1
Is there a GOOD way to do this in Eloquent short of reproducing this query with some raw() statements? Or does anyone have a suggestion about a better way to solve the problem of allowing for overriding configuration in this scenario? Thanks in advance!