0

I am using symfony 5.4 with doctrine-bundle 2.4. I've got an entity "sending" where I connect addresses with different connections

class Sending
{
...
    /**
     * @ORM\ManyToMany(targetEntity=Address::class, inversedBy="getSendingAsSender")
     * @ORM\JoinTable(name="sending_sender_address")
     */
    private $sender;
    /**
     * @ORM\ManyToMany(targetEntity=Address::class, inversedBy="getSendingAsRecipient")
     * @ORM\JoinTable(name="sending_recipient_address")
     */
    private $recipient;
}

and the corresponding address entity.

When creating an object of type sending I can access sender and recipient, so the definitions of the objects seem to be fine.

Now I want to create a list of all senders OR recipients by using querybuilder

$builder = $this->entitiyManager->getRepository(Sending::class)
    ->createQueryBuilder('s')
    ->join(Address::class, 'a')
...

This creates a

select ... from sending s inner join address a

without any connection data or on clauses and without the m:n join table in between. When adding a ->join('sending_sender_address','sa') before the address join it tells me, that there is not entity sending_sender_address.

What I finally need is a collection of address objects which are senders (or recipients) of any or selected sendings.

How do I do that connection properly and how can I choose which of the connection tables should be used?

Frank
  • 11
  • 1
  • Does this answer your question? [Doctrine query builder using inner join with conditions](https://stackoverflow.com/questions/15377079/doctrine-query-builder-using-inner-join-with-conditions) – KhorneHoly Nov 19 '21 at 08:40
  • Should have worked, thanks. Just Dylan's answer below was much closer to my needs. – Frank Nov 19 '21 at 10:18

1 Answers1

1

You could easily do something like:

    $builder = $this->entitiyManager->getRepository(Sending::class)
        ->createQueryBuilder('s');

    //check however you want which data you need
    if($type === ''){
        $builder->join('sa.sender', 'a');
    }else{
        $builder->join('sa.recipient', 'a');
    }

Or if $type is sender or recipient:

    $builder = $this->entitiyManager->getRepository(Sending::class)
        ->createQueryBuilder('s')
        ->join('s.'.$type, 'a')
    ;

You don't need to add a where clause to only get addresses related from your Sending entity, just select addresses from your join.

Dylan KAS
  • 4,840
  • 2
  • 15
  • 33
  • Yeah, that was the perfect hint (almost). I just had to swap Addresses to be the main part and join the sendings. Otherwise selecting addresses was empty. Now it works as wanted. Thanks a lot – Frank Nov 19 '21 at 10:15
  • You can still do it by having sending as the main part, but if you specifically want to select addresses you need to use `->addSelect('sa.sender')` or `->select('sa.sender')`, feel free to validate my answer if it helped you – Dylan KAS Nov 19 '21 at 11:02