【问题标题】:Is there a way with Doctrine for the parent and the children to have the same parent constraint?Doctrine 有没有办法让父母和孩子拥有相同的父母约束?
【发布时间】:2021-06-10 07:35:08
【问题描述】:

我使用 Doctrine 作为 PostgreSQL 的 ORM。我有很多实体,但这是我的限制:

一个系列有很多季节 一季有很多集

我在剧集和系列之间建立了关系,有一个函数 series->getEpisodes() (不经过季节)。

我的问题:有没有办法告诉 Doctrine 剧集和季节必须有相同的系列? 换句话说,添加一个约束,说一个孩子和他的父母必须有一个共同的父母?

因为没有这个限制,理论上剧集(子)和季节(父)有可能有不同的系列(但我现在通过应用程序避免了这种情况)。

【问题讨论】:

  • 关系episode->tv show好像是多余的,只要有episode->season->tv show就可以查询tv show的所有episode就好了。 db-fiddle.com/f/vLsURbLiG3SUzvJ7N5hrk7/1
  • 是的,它是多余的,但有时我想从一个系列中获得整个剧集。在这种情况下,将系列与剧集联系起来比穿越季节更好。我只想做出季节和剧集具有相同关系的约束。我想在教义配置中做出这个约束。
  • 为什么“更好”?以何种方式?我看不到好处。您只会增加复杂性并使您的应用程序更加脆弱。为您的应用程序采用自然模型。
  • 如果你有这个:serie->season->episode,如果你想要一个系列的所有剧集,你不能告诉 serie->getEpisodes(),你必须告诉 season- >getEpisodes where season.serie = 我想要的系列。这很好,因为您使用 sql 关系。但是,如果你在剧集和剧集之间建立直接关系,你可以更快(是的,它是毫秒)。
  • 你对它的工作原理感到困惑,但我猜你会在几年后意识到这一点。

标签: php doctrine-orm doctrine


【解决方案1】:

您必须创建自己的验证约束。 https://symfony.com/doc/current/validation/custom_constraint.html

/**
 * @Annotation
 */
class HasSameSeason extends Constraint
{
    public $message = 'The episode\'s serie must match the season serie';


    public function validatedBy()
    {
        return static::class.'Validator';
    }
}

class HasSameSeasonValidator extends ConstraintValidator
{
    public function validate($value, Constraint $constraint)
    {
        if (!$constraint instanceof HasSameSeason) {
            throw new UnexpectedTypeException($constraint, HasSameSeason::class);
        }

        if (!$value instanceof Episode) {
            throw new UnexpectedTypeException($value, Episode::class);
        }

        if ($episode->getSerie() !== $episode->getSeason()->getSerie()) {
            $this->context->buildViolation($constraint->message)->addViolation();
        }
    }
}


【讨论】:

  • 感谢您的回答!我希望不要从应用程序中执行此操作,而是更多地从数据库端(使用学说配置)执行此操作。但这似乎是不可能的..
猜你喜欢
  • 2016-09-10
  • 2015-03-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多