Reputation: 11265
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
Upvotes: 0
Views: 66
Reputation: 6922
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.
Upvotes: 1
Reputation: 515
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
Upvotes: 1
Reputation: 4860
Just add the following code to your ComCompany
class
public function getCityName()
{
return $this->cmpCity->getCitName();
}
Upvotes: 2