向Doctrine中的当前表添加虚拟列? [英] Adding virtual columns to current table in Doctrine?
问题描述
我在Symfony 1.4中使用了Doctrine 1.2。假设我有一个User模型,它有一个Profile。这些定义如下:
I'm using Doctrine 1.2 with Symfony 1.4. Let's say I have a User model, which has one Profile. These are defined as:
用户:
- id
- 用户名
- 密码
- created_at
- updated_at
- id
- username
- password
- created_at
- updated_at
个人资料:
- id
- user_id
- first_name
- last_name
- 地址
- 城市
- postal_code
- id
- user_id
- first_name
- last_name
- address
- city
- postal_code
我通常会收到如下数据:
I would normally get data 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(), 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语句看起来更像:
However, I would like for user to include "virtual" columns (not sure if this is the right term) such that fields from Profile actually look like they're a part of User. In other words, I'd like to see the print_r statement look more like:
Array (
"User" => Array (
"id" => 1,
"username" => "jschmoe",
"first_name" => "Joseph",
"last_name" => "Schmoe"
)
)
有没有办法通过我的schema.yml文件或通过我的Doctrine_Query对象来执行此操作?
Is there a way to do this either via my schema.yml file or via my Doctrine_Query object?
推荐答案
要做的就是使用定制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.
这篇关于向Doctrine中的当前表添加虚拟列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!