I’m working with a PHP framework that uses an ActiveRecord ORM (like Yii Framework or similar). I have a scenario where I need to query data from one or more tables (TableA, TableB) and present this data in an API response or view. However, the ideal structure for this output aligns with the field definitions of a specific model (CombinedModel), which isn’t directly mapped to the tables I’m querying.
The CombinedModel has a defined fields() method that specifies how its attributes should be structured for output (e.g., for API serialization). I want to leverage this existing structure without manually reshaping the data after fetching it with a different query.
What is an efficient and idiomatic way within an ActiveRecord ORM to execute a query that joins TableA and TableB, and then have the results formatted according to the fields() definition of CombinedModel?
I use a subquery in the from() clause. PHP:
$subQuery = TableA::find()
->select([
'a_id' => 'table_a.id',
'b_info' => 'table_b.info',
// ... more required fields
])
->joinWith(['tableB'], true, 'INNER JOIN');
$query = CombinedModel::find()
->from(['combined_data' => $subQuery])
->joinWith(['tableA' => function ($q) {
$q->on(['tableA.id' => 'combined_data.a_id']);
}], true, 'INNER JOIN');
When I fetch results using $query->all() or with a DataProvider I hope the output will be structured according to CombinedModel’s fields().
This seems to work for fetching the data.
What are any potential drawbacks or alternative patterns I should consider within an ActiveRecord ORM to reuse a model’s output structure for data fetched through a different query?
Is this subquery approach generally considered good practice for this scenario?
What are more suitable ORM features or patterns?
What are performance implications?