Cakephp 3中的平面结果集

时间:2016-01-03 08:01:32

标签: cakephp-3.0

由于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

处于同一级别

1 个答案:

答案 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;

  });