2014-11-25 76 views
0

我有3個實體,「講座」,「Cource」和「CourseImage」。與symfony和doctrine的關係問題

在課堂上講課,我有:

/** 
* @ORM\ManyToOne(targetEntity="Course", cascade={"persist"}) 
* @ORM\JoinColumn(name="courseId", referencedColumnName="courseId") 
*/ 
protected $course; 

,並在類課程,我有:

/** 
* @ORM\OneToMany(targetEntity="CourseImage", mappedBy="course") 
*/ 
protected $images; 

所有getter/setter方法是通過symfony的正確生成。

我做了一個自定義庫「LectureRepository」找回一些講座與本機查詢,其中我的代碼是:

public function findPopularByLocation($latitude, $longitude) 
    $rsm = new ResultSetMapping(); 
    $rsm->addEntityResult('Acme\DemoBundle\Entity\Lecture', 'l'); 
    $rsm->addFieldResult('l', 'lectureId', 'lectureId'); 
    $rsm->addFieldResult('l', 'latitude', 'latitude'); 
    $rsm->addFieldResult('l', 'longitude', 'longitude'); 
    $rsm->addFieldResult('l', 'start', 'start'); 
    $rsm->addMetaResult('l', 'courseId', 'courseId', true); 

    $sql = 'SELECT * , (3959 * ACOS(COS(RADIANS(?)) * COS(RADIANS(latitude)) * COS(RADIANS(longitude) - RADIANS(?)) + SIN(RADIANS(?)) * SIN(RADIANS(latitude)))) AS distance FROM lectures HAVING distance < 25 ORDER BY distance LIMIT 0 , 20;'; 
    $query = $this->getEntityManager()->createNativeQuery($sql, $rsm); 
    $query->setParameter(1, $latitude); 
    $query->setParameter(2, $longitude); 
    $query->setParameter(3, $latitude); 
    return $query->getResult(); 
} 

最後在我的控制器我有這樣的:

$popularLectures = $this 
    ->getDoctrine() 
    ->getManager() 
    ->getRepository('AcmeDemoBundle:Lecture') 
    ->findPopularByLocation($latitude, $longitude); 

哪個正確檢索我的講座,我也可以從講座中找回課程:

$popularLectures[0]->getCourse(); 

但是,當我嘗試:

$popularLectures[0]->getCourse()->getImages(); 

我沒有得到任何結果。我想我應該在本地查詢添加的東西,使其從數據庫中檢索圖像爲好,但我不知道怎麼和我的研究給了沒有回(任何幫助將不勝感激!

編輯: 課程中的getImages如下。

/** 
* Get images 
* 
* @return \Doctrine\Common\Collections\Collection 
*/ 
public function getImages() 
{ 
    return $this->images; 
} 
+0

我們可以看到'Course'實體的'getCourseImages()'和/或'getImages()'函數嗎? – 2014-11-25 10:48:36

+1

超出範圍,我想建議你看一下[CraueGeoBundle](https://github.com/craue/CraueGeoBundle)是一個**原理函數,用於計算Symfony2項目中的地理距離。 **您可以花兩分鐘時間查看距離查詢的[使用方法](https://github.com/craue/CraueGeoBundle#usage)部分。 – Matteo 2014-11-25 10:55:05

+0

@caCtus,我做了一個編輯。 @ Matteo,謝謝,我會的。 – 2014-11-25 10:56:56

回答

1

發現問題,我沒有inversedBy參數在那裏..無論如何感謝您的意見。

/** 
* @ORM\ManyToOne(targetEntity="Course", inversedBy="images", cascade={"persist"}) 
* @ORM\JoinColumn(name="courseId", referencedColumnName="courseId") 
*/ 
protected $course;