PROGRESS UPDATE:
I can create views and use this views for the models which work great for SELECT and UPDATE queries, but fail for INSERT queries (see code at bottom).
At this point, I feel like my options are try to modify the Eloquent models to target the real, non-view table for INSERTs, or maybe there's a pre-INSERT hook where I can create a record behind the scenes and silently convert any School::create() or $school->save() that's an INSERT into an INSERT on the real table, followed by an UPDATE on the view. Hmmm, maybe I can override function save() and static function create() on these models to use the proper table...
Ideally there's a more seamless way in MariaDB to add a 'synthetic' read-only column like this such that Laravel treats it like a proper table more universally.
CREATE VIEW schools_with_de_facto_foo AS
SELECT
`schools`.*,
IF(`schools`.foo_id, `schools`.foo_id, `districts`.foo_id) as de_facto_foo_id
FROM `schools`
LEFT JOIN `districts` on `districts`.id = `schools`.district_id;
CREATE VIEW studios_with_de_facto_foo AS
SELECT
`studios`.*,
IF(`studios`.foo_id, `studios`.foo_id,
IF(`schools`.foo_id, `schools`.foo_id, d.foo_id)
)
as de_facto_foo_id
FROM `studios`
LEFT JOIN `schools` on `schools`.id = `studios`.school_id
LEFT JOIN `districts` d on d.id = `schools`.district_id;
A view cannot be used for inserting if it fails any of the criteria for updating, and must also meet the following conditions:
- the view contains all base table columns that don't have default values
- no base table columns are present in view select list more than once
- the view columns are all simple columns, and not derived in any way. The following are examples of derived columns
- column_name + 25
- LOWER(column_name)
- (subquery)
- 9.5
- column1 / column2