Prabhu Khanna Mahadevan Prabhu Khanna Mahadevan - 5 months ago 13
PHP Question

Symfony3 foreign key relation entities not working

I have two tables

backup_policy
and
backup_settings
.
backup_policy
has a foreign key field called
backup_settings_id
with is mapped with
backup_settings
id
field. This is the query executed to create the relation between two tables ALTER TABLE
backup_policy_scheduler

ADD FOREIGN KEY (
backup_policy_id
) REFERENCES
backup_policy
(
id
)
.

Now the problem is, when I try this

$repository=$this->getDoctrine()>getRepository('AppBundle:BackupPolicy');
$settings = $repository->findAll();


code, the screen keep on loading and gives me maximum execution error. When I prepare a sql statement and do fetchAll() it fetches the result.

When I try to insert record it gives me below error
Type error: Argument 1 passed to AppBundle\Entity\BackupPolicy::setBackupSettings() must be an instance of AppBundle\Entity\BackupSettings, string given, called in /var/www/symfonyproject/src/AppBundle/Controller/BackupPolicyController.php on line 46

<?php

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
* BackupPolicy
*
* @ORM\Table(name="backup_policy")
*@ORM\Entity(repositoryClass="AppBundle\Entity\Repository\BackupPolicyRepository")
*/
class BackupPolicy
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer", nullable=false)
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;

/**
* @var \BackupSettings
*
* @ORM\ManyToOne(targetEntity="BackupSettings")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="backup_settings_id", referencedColumnName="id")
* })
*/
private $backupSettings;


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

/**
* Set backupSettings
*
* @param \AppBundle\Entity\BackupSettings $backupSettings
*
* @return BackupPolicy
*/
public function setBackupSettings(\AppBundle\Entity\BackupSettings $backupSettings = null)
{
$this->backupSettings = $backupSettings;

return $this;
}

/**
* Get backupSettings
*
* @return \AppBundle\Entity\BackupSettings
*/
public function getBackupSettings()
{
return $this->backupSettings;
}
}

Answer

You can only insert a BackupSettings entity.

In your controller line 46.

Not :

$backupPolicy->setBackupSettings('setting1');

But something like :

$repo=$this->getDoctrine()>getRepository('AppBundle:BackupSetting');
$backupPolicy->setBackupSettings($repo->findOneBy(array('name'=>'setting1'));