2014-05-15 37 views
0

我使用此代碼在doctrine2中執行zf2應用程序中的原生sql查詢。doctrin2 zf2原​​生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); 

這是結果

陣列(1){ [0] => 對象(管理員\實體\ SkillsExperience)#471(3){ [「id」:「Admin \ Entity \ SkillsExperience」:private] => string(1)「1」 [「idExperience」:「Admin \ Entity \ SkillsExperience」:private] => NULL [「idSkillsDetails 「:」管理\實體\技能體驗「:private] => object(Admin \ Entity \ SkillsDetails)#473(3){」id「:」Admin \ Entity \ SkillsDetails「:private] => NULL [」description「管理員\實體\ SkillsDetails 「:私人] => 串(18) 」skillsname「 [」 idSkill 「:」 管理員\實體\ SkillsDetails「:私人] => NULL } } }

我期望idSkillsDetails中的「Admin \ Entity \ SkillsDetails」,但它不是

我無法獲得

skd.description, skd.id_skill

哪能?

感謝

回答

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父親,用於進行連接的字段

我希望這對其他人有用。