[英]Ordering Doctrine Collection based on associated Entity when it is not possible to use the @orderBy annotation
[英]Is it possible to automatically create additonal properties on a doctrine entity, maybe by annotation
我有一个实体属性,并且基于该属性“名称”,我想构建另外 3 个属性,如果我可以通过注释、特征或扩展等来做到这一点,那就太棒了。
这是从用户以多种语言输入的数据。
有许多实体,在这些实体中,可以有许多要翻译的属性
这是一个示例实体
namespace App\Entity;
use App\Repository\EntityRepository;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity(repositoryClass=EntityRepository::class)
*/
class Entity
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="text")
*/
private $text;
}
我想“自动”将其扩展为 function 就好像它是这样写的
namespace App\Entity;
use App\Repository\EntityRepository;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity(repositoryClass=EntityRepository::class)
*/
class Entity
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="text")
*/
private $text;
/**
* @ORM\Column(type="datetime")
*/
private $textUpdatedAt;
/**
* @ORM\Column(type="text", nullable=true)
*/
private $textEng;
/**
* @ORM\Column(type="datetime", nullable=true)
*/
private $textEngUpdatedAt;
}
“可翻译”列可以是text
或string
( varchar
) 类型。 更新属性时将自动设置时间戳。 它用于“脏”跟踪。
我以为 Annotation 会是我的答案,但是当我尝试设置自定义注解时,我什至无法获得自动传入的属性名称。 我只会得到一个空的 class,如果我添加像 doctrine 文档给出的代码,我将不得不提供我正在寻找的所有信息。
通过使用嵌入,我有一个可重复使用的 class “分离”翻译和时间戳的问题并自动创建额外的列。
通过像这样创建一个可嵌入的 class
<?php
namespace App\Model;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
/**
* @ORM\Embeddable
*/
class TranslatableText
{
/**
* @ORM\Column(type="text")
*/
private $text;
/**
* @ORM\Column(type="datetime")
* @Gedmo\Timestampable(on="change", field="text")
*/
private $textUpdatedAt;
/**
* @ORM\Column(type="text", nullable=true)
*/
private $textEng;
/**
* @ORM\Column(type="datetime", nullable=true)
* @Gedmo\Timestampable(on="change", field="textEng")
*/
private $textEngUpdatedAt;
public function getId(): ?int
{
return $this->id;
}
public function getText(): ?string
{
return $this->text;
}
public function setText(string $text): self
{
$this->text = $text;
return $this;
}
public function getTextUpdatedAt(): ?\DateTimeInterface
{
return $this->textUpdatedAt;
}
public function getTextEng(): ?string
{
return $this->textEng;
}
public function setTextEng(?string $textEng): self
{
$this->textEng = $textEng;
return $this;
}
public function getTextEngUpdatedAt(): ?\DateTimeInterface
{
return $this->textEngUpdatedAt;
}
}
然后我可以在实体中的任何属性上使用此注释
/**
* @ORM\Embedded(class="\App\Model\TranslatableText")
*/
private $newsMy;
在数据库中,这会导致下表列
news_my_text
news_my_text_updated_at
news_my_text_eng
news_my_text_eng_updated_at
时间戳由 doctrine 可时间戳扩展自动设置。 访问数据也很简单
$entity->getNewsMy()->getText(); // gives "native" text
$entity->getNewsMy()->getTextEng(); // gives translated english text
我还有第二个可嵌入的 class 用于“字符串”类型的属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.