JBGO
JBGO

Reputation: 41

Doctrine and left join

I'm re-coding an old web app with Symfony 3 and I have to deal with Doctrine (not the fun part for me :/)

I'm trying to get a file from a table with the rights in another table :

Here's the query for MySQL (very basic I must say)

SELECT f.*, fr.access_type FROM files f
LEFT JOIN file_rights fr ON (fr.file_id = f.id AND fr.user_id = 2)
WHERE f.code = "xxxx"

So to do that with doctrine, I have my 2 entities "File" and "FileRights"

The goal was to do this in my controller :

$file = $em->getRepository('AppBundle:File')->getFile($code, $this->getUser());

if (!is_null($file) && !is_null($file->getRights()) {
    dump($file->getRights()->getAccessType());
}

and the repository looks like this :

public function getFile($code, $user) {
    return $this->createQueryBuilder('f')
        ->select('f, fr')
        ->leftJoin('f.rights', 'fr', Expr\Join::WITH, 'fr.user = :userId')
        ->where('f.code = :code')
        ->setParameter('userId', $user)
        ->setParameter('code', $code)
        ->getQuery()
        ->getOneOrNullResult();
}

but I dont know what to put in the entities ... I tried something like this but doesn't work ...

File.php

class File
{
    /**
     * @var int
     *
     * @ORM\Id
     * @ORM\Column(name="id", type="integer", options={"unsigned"=true})
     */
     private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="code", type="string", unique=true, length=20)
     */
     private $code;

     ...

     /**
      * @var \AppBundle\Entity\FileRights
      *
      * @ORM\OneToMany(targetEntity="AppBundle\Entity\FileRights", mappedBy="file")
      */
      private $rights;

FileRights.php

class FileRights
{
     ...

     /**
      * @var \AppBundle\Entity\File
      *
      * @ORM\ManyToOne(targetEntity="AppBundle\Entity\File")
      * @ORM\Column(name="file_id", type="string", length=20)
      */
      private $file;

but i have this error :

Notice: Undefined index: file

Could you help me with this very simple case ?

Thanks

Upvotes: 0

Views: 128

Answers (1)

JBGO
JBGO

Reputation: 41

Nice one ! There was 2 mistakes in the FileRights entity. It should have been :

/**
  * @var \AppBundle\Entity\File
  *
  * @ORM\ManyToOne(targetEntity="AppBundle\Entity\File", inversedBy="rights")
  * @ORM\JoinColumn(name="file_id", referencedColumnName="id")
  */
  private $file;

and in the controller :

if (!is_null($file) && !is_null($file->getRights()) {
    dump($file->getRights()[0]->getAccessType());
}

Thanks for the help :)

Upvotes: 0

Related Questions