h3g*_*0r_ 10 php doctrine dql doctrine-1.2
我需要一个简单的表格列.
例如,一个表"项目",带有列id
,name
和year
.
如果我做:
$q = Doctrine_Query::create()
->select('a.pro_id')
->from('fndr_proyecto a')
->where('a.pro_id =?',1);
$pro = $q->execute();
json_encode($pro->toArray());
Run Code Online (Sandbox Code Playgroud)
答案就是所有专栏
{"id":1,"name":"Project name","year":2013}
Run Code Online (Sandbox Code Playgroud)
但我只需要一列.我预计:
{"id":1}
Run Code Online (Sandbox Code Playgroud)
它与DQL一起使用,因为本机SQL工作正常.
ORM是使用Visual Paradigm自动构建的.
j0k*_*j0k 30
这是因为Doctrine用所有对象信息来补充响应,因此所有列都是如此.
你需要使用不同的水合方法,有很多方法,但让我们关注其中的5种方法:
HYDRATE_RECORD
,默认的HYDRATE_ARRAY
HYDRATE_NONE
HYDRATE_SCALAR
HYDRATE_ARRAY_SHALLOW
你需要HYDRATE_ARRAY_SHALLOW
水化方法.这就是原因.
HYDRATE_RECORD
$q = Doctrine_Query::create()
->select('a.pro_id')
->from('fndr_proyecto a')
->where('a.pro_id = ?',1);
$pro = $q->execute(array(), Doctrine_Core::HYDRATE_RECORD);
var_dump(json_encode($pro->toArray()));
Run Code Online (Sandbox Code Playgroud)
这将使用对象水合结果,并且还保持水合关系(如果在查询中使用leftJoin).因为它返回对象,我们需要调用toArray()
才能发送一个propre json:
[{"id":1,"name":"Project name","year":2013}]"
Run Code Online (Sandbox Code Playgroud)HYDRATE_ARRAY
$q = Doctrine_Query::create()
->select('a.pro_id')
->from('fndr_proyecto a')
->where('a.pro_id = ?',1);
$pro = $q->execute(array(), Doctrine_Core::HYDRATE_ARRAY);
var_dump(json_encode($pro));
Run Code Online (Sandbox Code Playgroud)
这将水合结果作为一个数组自动添加主键:
[{"id":"1","pro_id":"1"}]"
Run Code Online (Sandbox Code Playgroud)HYDRATE_NONE
$q = Doctrine_Query::create()
->select('a.pro_id')
->from('fndr_proyecto a')
->where('a.pro_id = ?',1);
$pro = $q->execute(array(), Doctrine_Core::HYDRATE_NONE);
var_dump(json_encode($pro));
Run Code Online (Sandbox Code Playgroud)
这不会保持结果,只返回值:
[["1"]]"
Run Code Online (Sandbox Code Playgroud)HYDRATE_SCALAR
$q = Doctrine_Query::create()
->select('a.pro_id')
->from('fndr_proyecto a')
->where('a.pro_id = ?',1);
$pro = $q->execute(array(), Doctrine_Core::HYDRATE_SCALAR);
var_dump(json_encode($pro));
Run Code Online (Sandbox Code Playgroud)
这将使select水合成结果,但使用键索引作为具有表别名的列名:
[{"a_pro_id":"1"}]"
Run Code Online (Sandbox Code Playgroud)HYDRATE_ARRAY_SHALLOW
$q = Doctrine_Query::create()
->select('a.pro_id')
->from('fndr_proyecto a')
->where('a.pro_id = ?',1);
$pro = $q->execute(array(), Doctrine_Core::HYDRATE_ARRAY_SHALLOW);
var_dump(json_encode($pro));
Run Code Online (Sandbox Code Playgroud)
这将使select水合结果但使用键索引作为列名而不使用表别名:
"[{"pro_id":"1"}]"
Run Code Online (Sandbox Code Playgroud)