Как использовать атрибут сущности, которая имеет много-много отношений с другой сущностью в symfony

У меня есть отношение ManyToMany между двумя организациями «Доктор» и «Страхование». Я настроил свою аннотацию ManyToMany в объекте Doctor, и в моей таблице Doctrine создала еще одну отдельную таблицу doctor_insurance. теперь я хотел бы использовать атрибут изображения страховки, к которой принадлежит доктор, в моей ветке, но я не знаю, как использовать этот атрибут

Entity Doctor

/**
 * @ORM\ManyToMany(targetEntity = "Doctix\MedecinBundle\Entity\Assurance", cascade = {"persist", "remove"})
 * @ORM\JoinColumn(nullable=true)
 */
private $assurance;

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

  /**
 * Add assurance
 *
 * @param \Doctix\MedecinBundle\Entity\Assurance $assurance
 *
 * @return Medecin
 */
public function addAssurance(\Doctix\MedecinBundle\Entity\Assurance $assurance)
{
    $this->assurance[] = $assurance;

    return $this;
}

/**
 * Remove assurance
 *
 * @param \Doctix\MedecinBundle\Entity\Assurance $assurance
 */
public function removeAssurance(\Doctix\MedecinBundle\Entity\Assurance $assurance)
{
    $this->assurance->removeElement($assurance);
}

/**
 * Get assurance
 *
 * @return \Doctrine\Common\Collections\Collection
 */
public function getAssurance()
{
    return $this->assurance;
}

Гарантия организации

  <?php

namespace Doctix\MedecinBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

 /**
  * Assurance
  *
  * @ORM\Table(name = "assurance")
  * 
  */
 class Assurance
 {
  /**
  * @var int
  *
  * @ORM\Column(name = "id", type = "integer")
  * @ORM\Id
  * @ORM\GeneratedValue(strategy = "AUTO")
  */
private $id;

 /**
 * @var string
 *
 * @ORM\Column(name = "nom", type = "string", length=40)
 */
public $nom;

 /**
 * @ORM\OneToOne(targetEntity = "Doctix\MedecinBundle\Entity\Logo", cascade = {"persist","remove","refresh"})
 * @ORM\JoinColumn(nullable=true)
 */
private $logo;



/**
 * Get id
 *
 * @return integer
 */
public function getId()
{
    return $this->id;
}

/**
 * Set nom
 *
 * @param string $nom
 *
 * @return Assurance
 */
public function setNom($nom)
{
    $this->nom = $nom;

    return $this;
}

/**
 * Get nom
 *
 * @return string
 */
public function getNom()
{
    return $this->nom;
}

/**
 * Set logo
 *
 * @param \Doctix\MedecinBundle\Entity\Media $logo
 *
 * @return Assurance
 */
public function setLogo(\Doctix\MedecinBundle\Entity\Media $logo = null)
{
    $this->logo = $logo;

    return $this;
}

/**
 * Get logo
 *
 * @return \Doctix\MedecinBundle\Entity\Media
 */
public function getLogo()
{
    return $this->logo;
}

}

Контроллер

   public function parametreAction(Request $request)
{

    $em = $this->getDoctrine()->getManager();
    $repo = $em->getRepository('DoctixMedecinBundle:Medecin');


    $medecin = $repo->findOneBy(array(
        'user' => $this->getUser(),
    ));

    $medecin->getAssurance();

    return $this->render('DoctixMedecinBundle:Medecin:parametre.html.twig', array(
        'medecin' => $medecin
    ));
}

Веточка

   <div class = "col-md-2">
       <div class = "box_list photo-medecin">
             <figure>
             <img src = "{{ vich_uploader_asset(medecin.assurance, 'logoFile') 
                 }}" class = "img-fluid" alt = ""> 
             </figure>

        </div>

Спасибо

Стоит ли изучать PHP в 2026-2027 годах?
Стоит ли изучать PHP в 2026-2027 годах?
Привет всем, сегодня я хочу высказать свои соображения по поводу вопроса, который я уже много раз получал в своем сообществе: "Стоит ли изучать PHP в...
Symfony Station Communiqué - 7 июля 2023 г
Symfony Station Communiqué - 7 июля 2023 г
Это коммюнике первоначально появилось на Symfony Station .
Symfony Station Communiqué - 17 февраля 2023 г
Symfony Station Communiqué - 17 февраля 2023 г
Это коммюнике первоначально появилось на Symfony Station , вашем источнике передовых новостей Symfony, PHP и кибербезопасности.
Управление ответами api для исключений на Symfony с помощью KernelEvents
Управление ответами api для исключений на Symfony с помощью KernelEvents
Много раз при создании api нам нужно возвращать клиентам разные ответы в зависимости от возникшего исключения.
1
0
51
2
Перейти к ответу Данный вопрос помечен как решенный

Ответы 2

<div class = "col-md-2">
{% for item in medecin.assurance %}
<div class = "box_list photo-medecin">
     <figure>
     <img src = "{{ vich_uploader_asset(item.logo , 'logoFile') 
         }}" class = "img-fluid" alt = ""> 
      </figure>
{% endfor %}
</div>
Ответ принят как подходящий

Уверенность означает Гарантия / Быть уверенным, так что более вероятно, что вы после Страхование, который является защита от возможной непредвиденной ситуации.

Также вы назвали первую сущность Врач, но использовали ее как Лекарство, поэтому, пожалуйста, измените ее, если врач является лекарством.

Вам нужно пересмотреть свои сущности, поскольку они полностью ошибочны:

Врач

use Doctix\MedecinBundle\Entity\Insurance;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;

class Doctor
{
    // ...

    /**
     * @ORM\ManyToMany(targetEntity = "Insurance", mappedBy = "doctors" cascade = {"persist", "remove"})
     * @ORM\JoinColumn(nullable=true)
     */
    private $insurances;

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

    public function addInsurance(Insurance $insurance)
    {
        if (!$this->insurances->contains($insurance))
        {
            $this->insurances->add($insurance);
            $insurance->addDoctor($this);
        }
    }

    public function removeInsurance(Insurance $insurance)
    {
        if ($this->insurances->contains($insurance))
        {
            $this->insurances->removeElement($insurance);
            $insurance->removeDoctor($this);
        }        
    }

    /**
     * @return Collection
     */
    public function getInsurances()
    {
        return $this->insurances;
    } 

    // ...
}

Страхование

use Doctix\MedecinBundle\Entity\Doctor;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;

class Insurance
{
    // ...

    /**
     * @ORM\ManyToMany(targetEntity = "Doctor", inversedBy = "insurances")
     * @ORM\JoinColumn(nullable=true)
     */
    private $doctors;

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

    public function addDoctor(Doctor $doctor)
    {
        if (!$this->doctors->contains($doctor))
        {
            $this->doctors->add($doctor);
            $doctor->addInsurance($this);
        }
    }

    public function removeDoctor(Doctor $doctor)
    {
        if ($this->doctors->contains($doctor))
        {
            $this->doctors->removeElement($doctor);
            $doctor->removeInsurance($this);
        }        
    }

    /**
     * @return Collection
     */
    public function getDoctors()
    {
        return $this->doctors;
    } 

    // ...
}

Обновлять

Контроллер

public function parametreAction(Request $request)
{
    $em = $this->getDoctrine()->getManager();
    $doctor = $em->getRepository('DoctixMedecinBundle:Medecin')->findOneBy(array(
        'user' => $this->getUser(),
    ));

    return $this->render('DoctixMedecinBundle:Medecin:parametre.html.twig', array(
        'doctor' => $doctor
    ));
}

Веточка

<div class = "col-md-2">
    <div class = "box_list photo-medecin">
        {% for insurance in doctor.insurances %}
        <figure>
            <img src = "{{ vich_uploader_asset(insurance.logo, 'logoFile') 
             }}" class = "img-fluid" alt = ""> 
        </figure>
        {% endfor %}
    </div>
</div>

Привет, @Trix, я начал с того, что врач может быть подписан на 1 или несколько страховок для своей клиники. И данная страховка гарантирует 1 или более врачей. Итак, если ваша организация верна, как я могу получить доступ к изображению страховки в мой файл веточки?

Mohamed Sacko 14.11.2018 12:00

Так что ты имеешь в виду под этим лекарством?

Pmpr 14.11.2018 12:07

извините за мой английский. Я говорю по-французски. По-французски медецин - врач по-английски.

Mohamed Sacko 14.11.2018 12:46

Проверьте Обновлять и рассмотрите возможность принятия и голосования, если это было полезно

Pmpr 14.11.2018 12:59

Другие вопросы по теме