简体   繁体   中英

doctrine get OneToMany relation results

I have 3 entities Advert , Applications , ApplicationFiles

Advert

/**
 * @ORM\OneToMany(targetEntity="App\Entity\Application", mappedBy="advert", orphanRemoval=true)
 */
private $applications;

Applications

    /**
     * @ORM\OneToMany(targetEntity="App\Entity\ApplicationFiles", mappedBy="app", orphanRemoval=true)
     */
    private $applicationFiles;

ApplicationsFiles

public function getFilePath(): string
    {
        return Uploader::APPLICATION_FILES.'/'.$this->getName();
    }

What I'm trying to do, is when I remove an Advert is to delete every Application with it's related ApplicationsFiles - which I did

My problem is that i can't manage to get the file names for each Advert so i could delete them.

All I could manage to do is to get only one result...

$appRepo = $m->getRepository(Application::class);
$rrr = $appRepo->getFilePath($post);
    dd($rrr);

getFilePath

/**
 * @param $s
 * @return mixed
 */
public function getFilePath($s)
{
    return $this->createQueryBuilder('a')
        ->andWhere('advert.id = :s')
        ->leftJoin('a.applicationFiles','applicationFiles')
        ->leftJoin('a.advert','advert')
        ->addSelect('applicationFiles.name')
        ->setParameter('s', $s)
        ->getQuery()
        ->getResult()
        ;
}

Dump -

array:1 [▼
  0 => array:2 [▼
0 => Application^ {#1186 ▶}
"name" => "hrm-01-application-5db552d60410c.doc"
 ]
]

Any help would be very appreciated:)

I think in this case you should query not Applications entity, but ApplicationFiles . Then you will get array of files to delete.

$filesToDelete = $m->getRepository(ApplicationsFiles::class)
                   ->createQueryBuilder('af')
                   ->innerJoin('af.application', 'a')
                   ->innerJoin('a.advert','advert')
                   ->andWhere('advert.id = :s')
                   ->setParameter('s', $post)
                   ->getQuery()
                   ->getReqult();

I'm not sure about $post var is it ID or Advert object? If it's object then we can remove second join and use only join with Application entity.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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