Remove the link between the two tables using the query builder.

I made a queryBuilder inside an object repository to remove a link between two tables.

I have two objects

Domain:

/**
 * @var int
 *
 * @ORM\Column(type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $id;

/**
 * @var string
 *
 * @ORM\Column(type="string", length=64)
 * @Assert\NotBlank
 * @Assert\Length(max="64")
 * @AppAssert\DomainName
 */
private $name;

// Some other fields

/**
 * @var SshKey[]|ArrayCollection
 *
 * @ORM\ManyToMany(targetEntity="AppBundle\Entity\SshKey", inversedBy="domains")
 * @ORM\JoinTable(name="domain_sshkey",
 *   joinColumns={@ORM\JoinColumn(referencedColumnName="id")},
 *   inverseJoinColumns={@ORM\JoinColumn(name="key_id", referencedColumnName="id")}
 * )
 */
private $sshKeys;

And SshKeys:

/**
 * @var int
 *
 * @ORM\Column(type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $id;

/**
 * @var \DateTime
 *
 * @Gedmo\Timestampable(on="create")
 * @ORM\Column(type="datetime")
 */
private $createdAt;

// Other fields

/**
 * @var Domain[]|ArrayCollection
 *
 * @ORM\ManyToMany(targetEntity="AppBundle\Entity\Domain", mappedBy="sshKeys")
 */
private $domains;

I am trying to remove links between these two tables when SshKeys idis in a field sshKeysinside the domain table.

So, I created this query constructor in my DomainRepository

public function deleteSshkeyDomainLink($invalidSshkey)
{
    $qb = $this->createQueryBuilder('d');

    $qb->delete()
       ->where($qb->expr()->in('ssh.id', ':ssh_keys_id'))
       ->setParameter('ssh_keys_id', $invalidSshkey)
       ->join('d.sshKeys', 'ssh')
    ;

    return $qb->getQuery()->execute();
}

But this QB returns this error

[Teaching \ ORM \ Query \ QueryException]
  [Semantic error] line 0, col 39 next to 'ssh.id IN (: s': Error: 'ssh' not defined.

[Teaching \ ORM \ Query \ QueryException]
  DELETE AppBundle \ Entity \ Domain d WHERE ssh.id IN (: ssh_keys_id)

, ssh is not defined, .

? , .

.

+4
1

, sshKey ( )?

removeSshKey, ,

public function removeSshKey(SshKey $key)
{
    $this->sshKeys->removeElement($key);

    return $this;
}

, , -

$domain = $this->getDoctrine()->getRepository('Domain')->find($domainId);
foreach ($domain->getSshKeys() as $sshKey)
{
    if ($sshKey->getId() == $invalidSshKeyId)
    {
        $domain->removeSshKey($sshKey);
    }   
}
$em = $this->getDoctrine()->getManager();
$em->flush();

+1

All Articles