I have 2 classes: Company:
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
How to add getter method to ComCompany
class to get City.citName
?
I have foreign keys
and Entity is generated properly, but there not method for get citName
from Company
class
Just add the following code to your ComCompany
class
public function getCityName()
{
return $this->cmpCity->getCitName();
}
You don't need no this getter method while you already have it in ComCity class. 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
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.
This can have terrible performance issues if you call getCityName in a loop so I thought it was worth mentioning it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.