我正在使用Doctrine 1.2和Symfony 1.4.假设我有一个User模型,它有一个Profile.这些定义为:
用户:
> id
>用户名
>密码
> created_at
> updated_at
轮廓:
> id
> user_id
> first_name
> last_name
>地址
>城市
> postal_code
我通常会得到这样的数据:
$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(),Doctrine_Core::HYDRATE_ARRAY); print_r($result);
Array ( "User" => Array ( "id" => 1,"username" => "jschmoe" ),"Profile" => Array ( "first_name" => "Joseph","last_name" => "Schmoe" ) )
但是,我希望用户能够包含“虚拟”列(不确定这是否是正确的术语),以便Profile中的字段实际上看起来像是User的一部分.换句话说,我想看看print_r语句看起来更像:
Array ( "User" => Array ( "id" => 1,"username" => "jschmoe","first_name" => "Joseph","last_name" => "Schmoe" ) )
有没有办法通过我的schema.yml文件或我的Doctrine_Query对象来做到这一点?
解决方法
做你想做的事就是使用
custom 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(); } }
然后使用连接管理器注册水化器:
$manager->registerHydrator('my_hydrator','Doctrine_Hydrator_MyHydrator');
然后你像这样保湿你的查询:
$query = Doctrine_Query::create() ->select('u.id,$username); $result = $query->fetchOne(array(),'my_hydrator'); print_r($result); /* outputs */ Array ( "User" => Array ( "id" => 1,"last_name" => "Schmoe" ) )
您可能需要对hyrdator逻辑进行一些细化以获得所需的确切数组结构.但这是做你想要的可接受的方式.