简体   繁体   English

检查是否存在实体关系。 (教义)

[英]Check if Entity relation does exist. (Doctrine)

I have relation for instance: 我有关系例如:

/**
 * @ORM\OneToOne(targetEntity="Model\Entity\Image")
 * @ORM\JoinColumn(name="image_id", referencedColumnName="id")
 */
protected $image;

And ordinary getter: 和普通的吸气剂:

public function getImage()
{
    return $this->image;
}

In my twig code I call it: 在我的树枝代码中,我称之为:

model.image.getImageURL()

But if there are no relation in database, like missing image_id , so getImage method will return null, and Exception on method getImageURL . 但是,如果在数据库中没有关系,就像缺少image_id,这样的getImage方法将返回null,和异常的方法getImageURL。 How can I avoid it clear. 我如何避免清除它。

My solution is: 我的解决方案是:

 protected function exist($model, $modelName) {
    if(isset($model)) {
        return $model;
    } else {
        $modelName = 'Model\Entity\\' . $modelName;
        return new $modelName();
    }
}

And getter like: 和吸气剂一样:

public function getImage()
{
    return $this->exist($this->image, 'Image');
}

But I don't like it, seem as not good solution for me. 但是我不喜欢它,对我来说似乎不是一个好的解决方案。 Can I do it more Symfony way, I assume that I am missing something? 我是否可以做些Symfony方式,假设我丢失了某些东西?

You're not really missing anything. 您并没有真正错过任何东西。

You have an optional relation in your entity which means the value can be null. 您的实体中有一个可选关系,这意味着该值可以为null。 so the "right" way to work with this situation is to check if the property is set before you access any methods on it. 因此处理这种情况的“正确”方法是在访问属性上的任何方法之前检查属性是否已设置。

Which means in a twig case: 在小树枝情况下意味着:

{% if model.image is not null %}
    {{ model.image.getimageUrl() %}
{% endif %}

and in the php case: 在PHP的情况下:

if($model->getImage() !== null) {
    $url = $model->getImage()->getImageUrl();
}

Other options would be changing the implementation of getImage: 其他选项将更改getImage的实现:

public function getImage() {
    return $this->image === null ? new Image() : $this->image;
}

or create a dedicated getImageUrl method directly in your model entity: 或直接在模型实体中创建专用的getImageUrl方法:

public function getImageUrl() {
    return $this->image !== null ? $this->image->getImageUrl() : '';
}

The only reason why it won't be filled is if it failed or couldn't find a relation. 无法填充的唯一原因是失败或找不到关系。 In this scenario, your workaround would return null too, because it does not exist. 在这种情况下,您的解决方法也将返回null ,因为它不存在。

What you can do is to check via: 您可以通过以下方法进行检查:

{% if model.image %}
  {{ model.image.imageUrl }}
{% endif %}

It searches for a get method so you can just use imageUrl and it will search for getImageUrl . 它搜索get方法,因此您可以只使用imageUrl ,它将搜索getImageUrl

There is also a thing when using relations, that Symfony won't do a reverse relation. 使用关系时还有一点,Symfony不会做反向关系。 I couldn't find the problem by myself, but a mate who struggled with it (he got my full trust in development decisions) told me that you have to manually add it and that it's a known and intentional thing in Symfony/Doctrine. 我自己找不到问题,但是一个与之抗争的伙伴(他对开发决策深信不疑)告诉我,您必须手动添加它,这在Symfony / Doctrine中是已知且故意的。

Let me give you a example with a OneToMany example: 让我举一个带有OneToMany示例的示例:

[Entity\\Human.php] [Entity \\ Human.php]

class Human
{

  /**
   * @ORM\ManyToOne(targetEntity="Race", inversedBy="race")
   * @JoinColumn
   *
   * A human can have one race, but a race can belong to many human
   */
  private $race;

  // using optional parameter so I can demonstrate it on one way..
  // If you want it to be required, remove " = null"
  // and also remove "if ($race && ..)" 
  public function setRace(Race $race = null)
  {
    $this->race = $race; // default from bin/console doctrine:generate:entities

    // Reverse check and add if not automatically done
    if ($race && ! $race->getHumans()->contains($this)) {
      $race->addHuman($this);
    }

    return $this; // default from bin/console doctrine:generate:entities
  }
}

and also the opposite site: 以及相对的站点:

[Entity\\Race.php] [Entity \\ Race.php]

class Race
{
  /**
   * @ORM\OneToMany(targetEntity="Human", mappedBy="race")
   */
  private $humans;

  public function __construct()
  {
    $this->humans = new ArrayCollection;
  }

  public function addHuman(Human $human)
  {
    $this->humans[] = $human; // default from bin/console doctrine:generate:entities

    // Custom reverse check and add
    if ($human->getRace() !== $this) {
      $human->setRace($this);
    }

    return $this; // default from bin/console doctrine:generate:entities
  }

  // also important for remove!
  public function removeHuman(Human $human)
  {
    $this->humans->removeElement($human);

    if ($human->getRace() !== null) {
      $human->setRace(null);
    }

    return $this;
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM