且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

向Doctrine中的当前表添加虚拟列?

更新时间:2023-12-01 10:40:22

要做的就是使用定制Hydrator

class Doctrine_Hydrator_MyHydrator extends Doctrine_Hydrator_ArrayHierarchyDriver
{
    public function hydrateResultSet($stmt)
    {
        $results = parent::hydrateResultSet($stmt);
        $array = array();

        $array[] = array('User' => array(
            'id'         => $results['User']['id'],
            'username'   => $results['User']['username'],
            'first_name' => $results['Profile']['first_name'],
            'last_name'  => $results['Profile']['last_name'],
        ));

        return $array();
    }
}

然后使用连接管理器注册hydrator: p>

Then register you hydrator with the connection manager:

$manager->registerHydrator('my_hydrator', 'Doctrine_Hydrator_MyHydrator');

然后,您可以像这样水合您的查询:

Then you hydrate your query like this:

$query = Doctrine_Query::create()
    ->select('u.id, u.username, p.first_name, p.last_name')
    ->from('User u')
    ->leftJoin('Profile p')
    ->where('u.username = ?', $username);

 $result = $query->fetchOne(array(), 'my_hydrator');
 print_r($result);

/* outputs */
Array (
    "User" => Array (
        "id" => 1,
        "username" => "jschmoe",
        "first_name" => "Joseph",
        "last_name" => "Schmoe"
    )
)

您可能需要稍微调整hyrdator逻辑,才能获得所需的精确数组结构。但这是可以接受的方式来做你想要的。

You might have to fines the hyrdator logic a little to get the exact array structure you want. But this the acceptable way to do what you want.