I have a many-to-one association in my entity and i want to grab another field to put the value in a db table instead of the title field.
my many are categories which can be set to a product. this all works fine. However i have an additional productcode field where i want to grab the category letter instead of title.
my category entity
namespace App\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Symfony\Component\HttpFoundation\File\File;
use Vich\UploaderBundle\Mapping\Annotation as Vich;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity()
* @ORM\HasLifecycleCallbacks()
*/
class Category
{
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="title", type="string")
*/
private $title;
/**
* @var string
*
* @ORM\Column(name="categoryletter", type="string")
*/
private $categoryletter;
public function getId(): ?int
{
return $this->id;
}
public function getTitle(): ?string
{
return $this->title;
}
public function setTitle(string $title): self
{
$this->title = $title;
return $this;
}
public function getCategoryletter(): ?string
{
return $this->categoryletter;
}
public function setCategoryletter(string $categoryletter): self
{
$this->categoryletter = $categoryletter;
return $this;
}
/**
* @return string
*/
public function __toString()
{
return $this->title;
}
}
in my product.php entity i have the following code
/**
* @var Category
*
* @ORM\ManyToOne(targetEntity="Category")
* @ORM\JoinColumn(name="category_id", referencedColumnName="id")
*/
private $category;
where i have an additional field to set a partical productcode based on category etc. but i don't want the category title but the associated categoryletter
/**
* @ORM\PrePersist
* @ORM\PreUpdate
*/
public function setProductcode()
{
{
$part = $this->category;
$this->productcode = $part;
}
I don't know how to grab another field of the category entity. If i change function __toString to categoryletter instead of title i do get the letter, but i want to stick with the title field just for general purpose.How do i get the categoryletter field? or is this not possible in a direct way?
If the orm is properly made between the two entities you can just use the getter :
/**
* set productCode
*
* @return Product
*/
public function setProductcode()
{
$category = $this->category;
$this->productcode = $category->getCategoryletter();
return $this;
}