Home > database >  How can I create a name on entity using a field coming from an other entity?
How can I create a name on entity using a field coming from an other entity?

Time:12-07

I am trying to give a new name in my BigCity Entity. I have an error that says that the Country Entity must be converted to string. As you can see in my code I wish to use the name of the country.

How can I do it ?

class BigCity
{
    #[ORM\Column(length: 255, unique: true)]
    private ?string $name = null;

    #[ORM\ManyToOne(inversedBy: 'bigCities')]
    private ?Country $country = null;

public function getName(): ?string
    {
        return $this->name;
    }

public function getCountry(): ?Country
    {
        return $this->country;
    }

public function getCityAndCountry(): ?string
    {
        $cityandcountry = $this->getName() . ', ' . $this->getCountry();
        return $cityandcountry;
    }
class Country
{
    #[ORM\Column(length: 255, unique: true)]
    private ?string $name = null;

    public function getName(): ?string
    {
        return $this->name;
    }

CodePudding user response:

In this line you should add the property name of country:

$cityandcountry = $this->getName() . ', ' . $this->getCountry();

when you say getCountry() that means all the object, it should be like this:

$cityandcountry = $this->getName() . ', ' . $this->getCountry()->getName();
  • Related