How to get associated table's displayField value instead foreignkey in controller

Cakephp 4
PHP 8
Not in view!
For example
id | post_id | user_id
1| 1| 1
2| 1| 3

expected
1 | post_title_1 | username1
2 | post_title_1 | username3

This is super easy. You want to get the data from the entity for the table which your table has other records associated with using a contain for those associations. For example:

You have the table “records” which contains (id, post_id, user_id). You created a function in your RecordEntity class to get the name of the “record”. In this case you would create:

protected function _getName() {
  //do your magic here and return the name

//See what data is available:
pr($this->_fields);
//You can access the post like this too: $this->get(‘post’), $this->get(‘user’)->get(‘username’) and so on.
}

And in your controller you would make sure that your find operation would contain the Posts and Users in the query to find the records. Like this: $recordsQuery = $this->Records->find()->contain([‘Posts’, ‘Users’])->all();

In the RecordsTable add this: $this->setDisplayField(‘name’); //Remember you need to create the function in the entity to get the name. And in that function you could access the Post and User data too since you have contained it in your find operation.

That is how you do it. Cheers

Thanks. I found another solution
$query
->select([‘country_name’ => ‘Countries.name’])
->innerJoinWith(‘Countries’);