我使用此代码在ztr2应用程序中使用doctrine2执行本机sql查询。
我使用此代码
$rsm = new ResultSetMapping();
$rsm->addEntityResult('Admin\Entity\SkillsExperience', 'skexp');
$rsm->addFieldResult('skexp', 'id', 'id');
$rsm->addFieldResult('skexp', 'idExperience', 'id_experience');
$rsm->addFieldResult('skexp', 'idSkillsDetails', 'id_skills_details');
$rsm->addJoinedEntityResult('Admin\Entity\SkillsDetails', 'skd','skexp','idSkillsDetails');
$rsm->addFieldResult('skd','description','description');
$rsm->addFieldResult('skd','idSkill','id_skill');
$sql = "
SELECT
skexp.id,
skexp.id_experience,
skexp.id_skills_details,
skd.description,
skd.id_skill
FROM skills_experience skexp
INNER JOIN skills_details skd
ON skd.id = skexp.id_skills_details
WHERE skexp.id_experience = $id_experience
ORDER BY skd.id_skill
";
$query = $this->getEntityManager()
->createNativeQuery($sql, $rsm)
->setParameter(1,$id_experience);
echo $query->getSQL();
$skexp = $query->getResult();
var_dump($skexp);
这是结果
array(1){ [0] => 对象(Admin \ Entity \ SkillsExperience)#471(3){ [ “ID”: “管理员\实体\ SkillsExperience”:私人] => string(1)“1” [ “idExperience”: “管理员\实体\ SkillsExperience”:私人] => 空值 [ “idSkillsDetails”: “管理员\实体\ SkillsExperience”:私人] => 对象(Admin \ Entity \ SkillsDetails)#473(3){ [ “ID”: “管理员\实体\ SkillsDetails”:私人] => 空值 [ “描述”: “管理员\实体\ SkillsDetails”:私人] => string(18)“skillsname” [ “idSkill”: “管理员\实体\ SkillsDetails”:私人] => 空值 } } }
我希望idSkillsDetails中有'Admin \ Entity \ SkillsDetails',但它不是
我无法获得
skd.description, skd.id_skill
我该怎么办?
感谢
答案 0 :(得分:1)
好的,我解决了
$rsm = new ResultSetMapping;
$rsm->addEntityResult('Admin\Entity\SkillsExperience', 'ske');
$rsm->addFieldResult('ske', 'id', 'id');
$rsm->addFieldResult('ske', 'idExperience', 'id_experience');
$rsm->addJoinedEntityResult('Admin\Entity\SkillsDetails' , 'skd', 'ske', 'idSkillsDetails');
$rsm->addFieldResult('skd', 'idx', 'id');
$rsm->addFieldResult('skd', 'description', 'description');
$rsm->addJoinedEntityResult('Admin\Entity\Skills' , 'sk', 'skd', 'idSkill');
$rsm->addFieldResult('sk','idx2','id');
$sql = <<<EOT
SELECT
ske.id,
ske.id_experience,
skd.id as idx,
skd.description,
skd.id_skill,
sk.id as idx2
FROM skills_experience ske
LEFT JOIN skills_details skd
ON skd.id = ske.id_skills_details
LEFT JOIN skills sk
ON sk.id = skd.id_skill
WHERE id_experience = ?
ORDER BY sk.id
EOT;
$query = $this->em->createNativeQuery($sql,$rsm);
$query->setParameter(1,$id_experience);
$array = $query->getResult();
首先应该注意的是,当在不同的表中存在具有相同名称的字段时,必须指定别名。
将连接添加到本机查询时,必须使用以下方法
addJoinedEntityResult
有4个参数
1)执行连接的类/实体
2)在查询中使用连接的表的别名
3)查询中使用的父表的别名
4)连接到女儿的父实体的字段(在我的情况下idSkillsDetails加入第一个和第二个idSkill加入)
在类addFieldResult父亲的方法中,您不能使用用于进行连接的字段
我希望它对别人有用。