2011-04-10 57 views
1

我使用Doctrine ORM 2。 我得到了以下實體類。PHP Doctrine 2 ORM:非實體對象作爲實體中的屬性

/** 
* @Entity 
* @Table(name="objects") 
*/ 
class MyObject 
{ 
    /** 
    * @Id 
    * @GeneratedValue 
    * @Column(type="integer") 
    */ 
    private $id; 

    /** 
    * @var Coordinate 
    */ 
    private $coordinate; 
} 

class Coordinate 
{ 
    private $x; 
    private $y; 
    private $z; 
} 

我要實現的3座標在一個單獨的類值PHP中更好的操控性。但在數據庫中,我希望將3個值包含在數據庫表「對象」中。

有誰知道如何做到這一點?

問候

編輯: 我發現了一個解決方法,但它不是最好的。

/** 
    * 
* @var integer 
* @Column(type="integer") 
*/ 
private $x; 
/** 
* 
* @var integer 
* @Column(type="integer") 
*/ 
private $y; 
/** 
* 
* @var integer 
* @Column(type="integer") 
*/ 
private $z; 

public function getCoordinate() 
{ 
    return new Coordinate($this->x, $this->y, $this->z); 
} 

public function setCoordinate(Coordinate $coord) 
{ 
    $this->x = $coord->getX(); 
    $this->y = $coord->getY(); 
    $this->z = $coord->getZ(); 
} 

回答

3

最簡單的方法是將該字段設置爲使用「對象」映射類型。

/** 
* @Column(type="object") 
*/ 
private $coordinate; 

那麼無論你把在該領域對象的類,學說會自動當它插入和拔出數據庫的序列化和unserialise。

另一種方法是製作自定義映射類型 - http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/cookbook/custom-mapping-types.html。這使用與對象類型相同的方法,但允許您精確指定對象在PHP和SQL之間的轉換方式。

如果你使用這種方法有一個映射類型命名爲座標,那麼你就只需要聲明本作的領域:

/** 
* @Column(type="coordinate") 
*/ 
private $coordinate; 

一個缺點而據我可以看到有沒有辦法解決它,是您只能爲該字段使用一個數據庫列。所以你不能通過x,y或z分別使用DQL進行排序。

0

只需配置你的getter和setter即可。這樣在你的實體

public function setCoordinate (Coordinate $coordinate) { 

$coordinateArr = $coordinate->getArrayCopy(); 

$this->coordinate = serialize($coordinateArr); 

} 

public function getCoordinate() { 

$coordinateArr = unserialize($this->coordinate); 

$coordinate = new Coordinate(); 
$coordinate->exchangeArray($coordinateArr); 
return $coordinate; 

} 

但是如果你想SQL搜索,你需要使用LIKE。

相關問題