[英]Doctrine2 getters for associations
I have 2 classes: Company: 我有2节课:公司:
class ComCompany
{
/**
* @var integer
*
* @ORM\Column(name="cmp_id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $cmpId;
/**
* @var string
*
* @ORM\Column(name="cmp_name", type="string", length=100, nullable=true)
*/
private $cmpName;
/**
* @var integer
*
* @ORM\Column(name="cmp_code", type="integer", nullable=true)
*/
private $cmpCode;
/**
* @var \Catalog\WebBundle\Entity\ComCity
*
* @ORM\ManyToOne(targetEntity="Catalog\WebBundle\Entity\ComCity")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="cmp_city", referencedColumnName="cit_id")
* })
*/
private $cmpCity;
public function getCmpName()
{
return $this->cmpName;
}
public function getCmpCode()
{
return $this->cmpCode;
}
public function getCmpCity()
{
return $this->cmpCity;
}
}
And city 和城市
class ComCity
{
/**
* @var integer
*
* @ORM\Column(name="cit_id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $citId;
/**
* @var string
*
* @ORM\Column(name="cit_name", type="string", length=255, nullable=true)
*/
private $citName;
public function getCitId()
{
return $this->citId;
}
public function getCitName()
{
return $this->citName;
}
}
This 2 tables have associations Company.comCity = City.citId
这2个表具有关联
Company.comCity = City.citId
How to add getter method to ComCompany
class to get City.citName
? 如何将getter方法添加到
ComCompany
类以获取City.citName
?
I have foreign keys
and Entity is generated properly, but there not method for get citName
from Company
class 我有
foreign keys
并且Entity正确生成,但是没有从Company
类获取citName
方法
Just add the following code to your ComCompany
class 只需将以下代码添加到您的
ComCompany
类中
public function getCityName()
{
return $this->cmpCity->getCitName();
}
You don't need no this getter method while you already have it in ComCity class. 当您已经在ComCity类中使用此getter方法时,则不需要它。 Because adding it (like answer suggested) is making duplicate code.
因为添加它(如建议答案)会使代码重复。 You should use
你应该用
$company->getCmpCity()->getCitName()
instead 代替
And also: https://en.wikipedia.org/wiki/Don%27t_repeat_yourself 并且: https : //en.wikipedia.org/wiki/Don%27t_repeat_yourself
Both answers provided are absolutely correct. 提供的两个答案都是绝对正确的。 However, take into account that if you're using lazy loading an extra query will be triggered each time you call getCityName unless you use a JOIN in your DQL/Query Builder.
但是,请考虑到,如果您使用的是延迟加载,则每次调用getCityName都会触发一个额外的查询,除非您在DQL /查询生成器中使用了JOIN。
This can have terrible performance issues if you call getCityName in a loop so I thought it was worth mentioning it. 如果您在循环中调用getCityName,可能会遇到严重的性能问题,因此我认为值得一提。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.