由于contains
子句,我有一个返回嵌套结果集的查询。无论如何我是否可以扁平化并将嵌套子项放在父级别?
查询:
$results = $this->find()
->select(['Users.id', 'Profiles.firstname', 'Profiles.lastname', 'Profiles.title', 'Profiles.city', 'Profiles.state'])
->contain(['Profiles' => function($q) use ($searchStr) {
return $q
->where(['OR' => [
'firstname LIKE ' => $searchStr . '%',
'lastname LIKE ' => $searchStr . '%'
]]);
}]);
返回结果集:
--> 0(object)
--> id 5
--> profile(array)
=> firstname Sam
=> lastname Johnson
=> title CEO
=> city Champaign
=> state IL
我希望个人资料数据与id
答案 0 :(得分:2)
您可以使用map
中描述的Query Builder: Queries are collection objects方法。
$results = $this->Users->find()
->select(['Users.id', 'Profiles.firstname', 'Profiles.lastname'])
->contain(['Profiles'])
->map(function($row){
$row->firstname = $row->profile->firstname;
$row->lastname = $row->profile->lastname;
unset($row->profile); // Remove this if you want to keep the 'profile' array.
return $row;
});
此外,您可以对virtual fields使用相同的方法:
App\Model\Entity\User
protected function _getFirstname () {
return $this->_properties['profile']['firstname'];
}
protected function _getLastname () {
return $this->_properties['profile']['lastname'];
}
App\Controller\UsersController
$results = $this->Users->find()
->select(['Users.id', 'Profiles.firstname', 'Profiles.lastname'])
->contain(['Profiles'])
->map(function($row){
// Right side of the operator will call User::_get*()
// Left side of the operator will set the property to the object
$row->firstname = $row->firstname;
$row->lastname = $row->lastname;
unset($row->profile);
return $row;
});