我使用Doctrine ORM 2。我得到了以下实体类。
/**
* @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个值包含在数据库表"objects"中。
有人知道如何实现这一点吗?
问好编辑:我找到了一个变通办法,但不是最好的。
/**
*
* @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();
}
最简单的方法是将该字段设置为使用"object"映射类型。
/**
* @Column(type="object")
*/
private $coordinate;
然后,无论您在该字段中放入什么类的对象,Doctrine将在插入和拔出数据库时自动序列化和反序列化。
另一种方法是创建一个自定义映射类型- http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/cookbook/custom-mapping-types.html。这使用与对象类型相同的方法,但允许您指定对象如何在PHP和SQL之间进行转换。
如果您使用的方法有一个名为坐标的映射类型,那么您只需为字段声明:
/**
* @Column(type="coordinate")
*/
private $coordinate;
一个缺点,据我所知,没有办法绕过它,是您只能为字段使用一个数据库列。因此,您将无法使用DQL分别按x, y或z排序。
配置你的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