以下のようなEntity\User下のメソッドにて
public function getFriendsNames(){
$friend_names = collection($this->friends)
->extract(function ($friend) {
return $friend->name;
})
->toList();
$friend_names = array_unique($friend_names);
return $friend_names;
}
Userの友人の名前を配列で返すメソッドですが,二行目の$this->friendsの部分では友人のレコードがロードされている前提で実装されています.
このままでは呼び出し側が予めUser取得時にcontainでFriendをロードしておかないとエラーがでてしまい,本来関連するFriendがあるにもかかわらず友達がいないかのような挙動をしてしまいます.
こういう状況では以下を参考に関連するレコードをロードするメソッドを記述しておくと呼び出し側の責任がなくなります.
public function getFriendsNames(){
$friend_names = collection($this->friends)
->extract(function ($friend) {
return $friend->name;
})
->toList();
$friend_names = array_unique($friend_names);
return $friend_names;
}
// 以下追加
protected function _getFriends() {
$friends = TableRegistry::get('Friends');
return $friends->find('all')
->where(['user_id' => $this->id])
->all();
}


