I’m trying to create a virtual field for an entity using attributes from associated entities. Creating the virtual field works fine but I don’t know how to get hold of the associated entity attributes.
The website is for a house builder. They have a number of housing developments each of which has a number of plots for sale. Each of those plots has a house of a specific design on it and each of these houses is of a specific type that has a certain number of bedrooms.
What I’m trying to create is a virtual field in the development that’s a simple array of all the different numbers of bedrooms on that development. So, for example, if there are houses with one bedroom, houses with two bedrooms and houses with four bedrooms, the array would be [1,2,4].
In the table definition for the developments I have the following association -
$this->hasMany('Plots', [
'foreignKey' => 'development_id',
]);
In the table defintion for the plots I have -
$this->belongsTo('Houses', [
'foreignKey' => 'house_id',
'joinType' => 'INNER',
]);
In the table definition for the houses I have -
$this->belongsTo('HouseTypes', [
'foreignKey' => 'house_type_id',
'joinType' => 'INNER',
]);
Then the housetype entity has an attribute called ‘rooms’.
What I want to do when I create the virtual field is cycle through all the plots in the development to find the number of rooms in each plot like this -
protected function _getRoomsArray()
{
$rooms = [];
foreach($this->available_plots as $plot)
{
$rooms[] = $plot->house->house_type->rooms;
}
$rooms = array_unique($rooms);
sort($rooms);
return $rooms;
}
Obviously the $rooms[] = $plot->house->house_type->rooms;
line doesn’t work.
Anybody got any idea how to do something like this?