Hi, I use CakePHP 4.
I have two related classes, addresses and nations for the tables:
Nations
Addresses (FK nation_id)
I have created an virtual field _getFullAddress() in the Address entitiy and want to display the name of the realted Nation. Is this possible? How can I access the related entity data in an entity file?
Thanks!
If you retrieve your addresses so that they contain
Nations, then the data will be available for your _getFullAddress()
method on $this->nation
in your Address entity.
//In Address entity, something like this
public function _getFullAddress() {
return $this->city . ' ' .$this->nation->name;
}
If you neglect to contain
Nations the method will throw an error so you might want to work out a way to guarantee Address entities always contain the expected data or make your entity method tolerate missing contained data.
1 Like
Thanks! I did not understand where I have to use contain
so that the data is available in the entity file (e.g. in the Controller where I use $tmp->address->full_address
) … simple as that; problem solved!