Insert a field into joint-table doctrine - symfony

I want to insert into my joint-table RoleUser idUser and idRole ,but in the function I should add an object user and role
How can I do that?
the joint table RoleUser :
/**
* RoleUser
*
* #ORM\Table(name="role_user", indexes={#ORM\Index(name="fk_role_user_id", columns={"ref_user_id"}), #ORM\Index(name="fk_role_id", columns={"ref_role_id"})})
* #ORM\Entity(repositoryClass="AppBundle\Repository\RoleUserRepository")
*/
class RoleUser
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
/**
* #var \AppBundle\Entity\Role
*
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\Role")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="ref_role_id", referencedColumnName="id")
* })
*/
private $refRole;
/**
* #var \AppBundle\Entity\User
*
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\User")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="ref_user_id", referencedColumnName="id")
* })
*/
private $refUser;
/**
* #param Role $refRole
*/
public function setRefRole(\AppBundle\Entity\Role $refRole)
{
$this->refRole = $refRole;
}
/**
* #param User $refUser
*/
public function setRefUser(\AppBundle\Entity\User $refUser)
{
$this->refUser= $refUser;
}
}
In my controller I want to insert the following (for a particular case I should insert in the background, the user can't choose his role):
$user = new User();
$role= new Role();
$roleUser =new RoleUser();
$roleUser->setRefUser($user->getId());
$roleUser->setRefRole(1);
but I konw that I should pass a user and a role :
$roleUser->setRefUser($user);
$roleUser->setRefRole($role);

You need to use a relation ManyToMany instead of OneToMany and remove your Entity RoleUser. you can follow the next example in the documentation official, to mapping this kind of relations.
For the save:
In this case you need to add in the two entities this relation:
<?php
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* Location
*
* #ORM\Table(name="location")
* #ORM\Entity
*/
class Location
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* <p>Represent the </p>
* #ORM\ManyToMany(targetEntity="LogoLocation", mappedBy="locations")
*/
private $logoLocationCurse;
/**
* Location constructor.
*/
public function __construct()
{
$this->logoLocationCurse = new ArrayCollection();
}
public function addlogoLocationCurse(LogoLocation $location)
{
$this->logoLocationCurse->add($location);
$location->addLocations($this);
}
public function removeLogo(LogoLocation $location)
{
$this->logoLocationCurse->removeElement($location);
$location->removeLocation($this);
}
}
<?php
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use \DateTime;
/**
* Class LogoLocation
* #ORM\Table(name="logo_location_curso")
* #ORM\Entity
*/
class LogoLocation
{
/**
* #var integer
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* Many Users have Many Groups.
* #ORM\ManyToMany(targetEntity="Location", inversedBy="logocurso")
* #ORM\JoinTable(name="logo_locations")
*/
private $locations;
/**
* LogoLocation constructor.
*/
public function __construct()
{
$this->locations = new ArrayCollection();
}
/**
* #param Location $location
*/
public function addLocations(Location $location)
{
$this->locations->add($location);
}
/**
* #param Location $location
*/
public function removeLocation(Location $location)
{
$this->locations->removeElement($location);
}
/**
*
*/
public function removeLocations()
{
/** #var Location $location */
foreach ($this->locations as $location) {
$location->removeLogo($this);
}
}
}
and make the flush

Related

not defined as association in doctrine orm validate

i have two entities named UserCode and Question that have relation between question columns and when i run doctrine:schema:validate it s ok
but my problem is when i add
#ORM\Entity(repositoryClass="AppBundle\Repository\UserCodeRepository")
at top of UserCode entity i get this error !!
* The association AppBundle\Entity\UserCode#question refers to the inverse side field AppBundle\Entity\Question#question which is not defined as association.
* The association AppBundle\Entity\UserCode#question refers to the inverse side field AppBundle\Entity\Question#question which does not exist.
Question entity :
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use AppBundle\Entity\UserCode;
/**
* Question
*
* #ORM\Table(name="question")
* #ORM\Entity(repositoryClass="AppBundle\Repository\QuestionRepository")
*/
class Question
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="question", type="text")
* #ORM\OneToMany(targetEntity="AppBundle\Entity\UserCode", mappedBy="question")
*/
private $question;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set question
*
* #param string $question
*
* #return Question
*/
public function setQuestion($question)
{
$this->question = $question;
return $this;
}
/**
* Get question
*
* #return string
*/
public function getQuestion()
{
return $this->question;
}
}
and this is my UserCode entity:
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\ORM\Mapping\JoinColumn;
use Symfony\Component\Validator\Constraints as Assert;
/**
* UserCode
*
* #ORM\Table(name="user_code")
* #ORM\Entity(repositoryClass="AppBundle\Repository\UserCodeRepository")
*/
class UserCode
{
/**
* #var int
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\Question", inversedBy="question")
* #ORM\JoinColumn(name="question", referencedColumnName="id")
*/
private $question;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set question
*
* #param \AppBundle\Entity\Question $question
*
* #return UserCode
*/
public function setQuestion(\AppBundle\Entity\Question $question = null)
{
$this->question = $question;
return $this;
}
/**
* Get question
*
* #return \AppBundle\Entity\Question
*/
public function getQuestion()
{
return $this->question;
}
}
remove
#ORM\JoinColumn(name="question", referencedColumnName="id")
from
UserCode entity and
* #var string
*
* #ORM\Column(name="question", type="text")
from question entity
it will work perfectly :)

Error creating relationship with FOSUserBundle and custom entity with easy-extends

I followed this documentation in sonata, step by step and it worked.
Then I added a new entity and tried to generate a relation many to many to user entity, and when I validate it return this error
$ bin/console doctrine:schema:validate
Mapping
-------
[FAIL] The entity-class AppBundle\Entity\Business mapping is invalid:
* The association AppBundle\Entity\Business#user refers to the owning side field Application\Sonata\UserBundle\Entity\User#business which does not exist.
Database
--------
[OK] The database schema is in sync with the mapping files.
This are my two entities
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
/**
* Business
*
* #ORM\Table(name="business")
* #ORM\Entity(repositoryClass="AppBundle\Repository\BusinessRepository")
*/
class Business
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="BusinessName", type="string", length=255)
*/
private $businessName;
/**
* #var string
*
* #ORM\Column(name="fantasyName", type="string", length=255)
*/
private $fantasyName;
/**
* #var string
*
* #ORM\Column(name="cuit", type="string", length=13)
*/
private $cuit;
/**
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\BankAccountType", inversedBy="business")
*/
private $bankAccountType;
/**
* #var \DateTime $created
*
* #Gedmo\Timestampable(on="create")
* #ORM\Column(type="datetime")
*/
private $created;
/**
* #var \DateTime $updated
*
* #Gedmo\Timestampable(on="update")
* #ORM\Column(type="datetime")
*/
private $updated;
/**
* #ORM\ManyToMany(targetEntity="\Application\Sonata\UserBundle\Entity\User", mappedBy="business")
*/
private $user;
/**
* #var bool
*
* #ORM\Column(name="isActive", type="boolean")
*/
private $isActive = true;
And this
namespace Application\Sonata\UserBundle\Entity;
use Sonata\UserBundle\Entity\BaseUser as BaseUser;
use Doctrine\ORM\Mapping as ORM;
/**
* This file has been generated by the SonataEasyExtendsBundle.
*
* #link https://sonata-project.org/easy-extends
*
* References:
* #link http://www.doctrine-project.org/projects/orm/2.0/docs/reference/working-with-objects/en
*/
class User extends BaseUser
{
/**
* #var int $id
*/
protected $id;
/**
* #ORM\ManyToMany(targetEntity="\AppBundle\Entity\Business", inversedBy="user")
* #ORM\JoinTable(name="business_user")
*/
private $business;
/**
* Constructor
*/
public function __construct()
{
parent::__construct();
$this->business = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Get id.
*
* #return int $id
*/
public function getId()
{
return $this->id;
}
}
Any idea?
Here is my code for the same thing and it works.
class Role
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\ManyToMany(targetEntity="wizai\WMC\UserBundle\Entity\User", mappedBy="customRoles", fetch="EAGER")
*/
private $users;
public function __construct()
{
$this->users = new ArrayCollection();
}
}
class User extends BaseUser
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\ManyToMany(targetEntity="wizai\WMC\UserBundle\Entity\Role", inversedBy="users", fetch="EAGER")
* #ORM\JoinTable(name="user_role",
* joinColumns={#ORM\JoinColumn(name="user", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="role", referencedColumnName="id")}
* )
*/
protected $customRoles;
/**
* User constructor.
*/
public function __construct()
{
$this->customRoles = new ArrayCollection();
}
}
if its still not possible, can you first run a migration or a force update ?
Commands
bin/console doctrine:migrations:diff
bin/console doctrine:migrations:migrate
if not, then try.
bin/console doctrine:schema:update --force --complete

Doctrine2 cascade create

Here some context information: I'm building a Symfony2 application with Doctrine2 and FOSRestBundle.
My problem: I want to be able to create a parent with his children with just one JSON and one database access.
My JSON looks like this:
{
"name": "TEST_NAME",
"info": "TEST_INFO",
"cmts": [
{
"cmt": "CMT1",
"info": "INFO1"
},
{
"cmt": "CMT2",
"info": "INFO2"
},
{
"cmt": "CMT3",
"info": "INFO3"
}
]
}
Here is my TEST entity:
<?php
namespace App\Bundle\DemoBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Test
*
* #ORM\Table(name="Test")
* #ORM\Entity(repositoryClass="App\Bundle\DemoBundle\Entity\TestRepository")
*/
class Test
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255)
* #Assert\NotBlank()
*/
private $name;
/**
* #var string
*
* #ORM\Column(name="info", type="string", length=255, nullable=true)
*/
private $info;
/**
* #ORM\OneToMany(targetEntity="TestCmt", mappedBy="test", fetch="EAGER", orphanRemoval=true, cascade={"merge", "remove", "persist"})
*/
protected $cmts;
/**
* Constructor
*/
public function __construct()
{
$this->cmts = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Add cmts
*
* #param \App\Bundle\DemoBundle\Entity\TestCmt $cmts
* #return Test
*/
public function addCmt(\App\Bundle\DemoBundle\Entity\TestCmt $cmts)
{
$this->cmts[] = $cmts;
return $this;
}
/**
* Remove cmts
*
* #param \App\Bundle\DemoBundle\Entity\TestCmt $cmts
*/
public function removeCmt(\App\Bundle\DemoBundle\Entity\TestCmt $cmts)
{
$this->cmts->removeElement($cmts);
}
/**
* Get cmts
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getCmts()
{
return $this->cmts;
}
// other getters/setters...
}
And my TESTCMT entity:
<?php
namespace App\Bundle\DemoBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* TestCmt
*
* #ORM\Table(name="TestCmt")
* #ORM\Entity(repositoryClass="App\Bundle\DemoBundle\Entity\TestCmtRepository")
*/
class TestCmt
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="cmt", type="string", length=255)
*/
private $cmt;
/**
* #var string
*
* #ORM\Column(name="info", type="string", length=255, nullable=true)
*/
private $info;
/**
* #var Test
*
* #ORM\ManyToOne(targetEntity="Test", inversedBy="cmts")
* #ORM\JoinColumn(name="test_id", referencedColumnName="id")
**/
private $test;
/**
* Set test
*
* #param \App\Bundle\DemoBundle\Entity\Test $test
* #return TestCmt
*/
public function setTest(\App\Bundle\DemoBundle\Entity\Test $test = null)
{
$this->test = $test;
return $this;
}
/**
* Get test
*
* #return \App\Bundle\DemoBundle\Entity\Test
*/
public function getTest()
{
return $this->test;
}
}
And finaly my postTestAction():
public function postTestAction(Request $request)
{
$entity = $this->deserialize($request, 'App\DemoBundle\Entity\Test');
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
return $entity;
}
When I send the JSON, TEST and TESTCMTs are created. Nevertheless, all "test_id" from the created TESTCMTs are "null"... And that's my problem!
EDIT: with SQL Server Profiler, I can see that Doctrine make that Transact SQL request:
INSERT INTO TESTCMT (test_id, cmt, info) VALUES (null, 'CMT', 'INFO')
I don't know why Doctrine can't send the test_id... TEST is created before TESTCMT, so "test_id" should be reachable for Doctrine to create the associate TESTCMTs.
Can someone helped me to fix it? :)
Remove #ORM\GeneratedValue(strategy="AUTO") and it won't let the DB generate a new id for the Entity

One-To-Many Relation in Symfony 2 with Doctrine

I've looked at literally tons of questions/answers on Stack Overflow and other places on the web, but cannot find a resolution to this problem.
Before I explain the problem, I have:
stripped back my entities so that they only have the minimum attributes and methods
have cleared the doctrine query cache / metadata cache
dropped and recreated the schema
checked my spelling
I have the following two entities:
<?php
namespace Docker\ApiBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
*/
class Source
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\Column(type="integer")
* #ORM\ManyToOne(targetEntity="Project",inversedBy="sources")
* #ORM\JoinColumn(referencedColumnName="id")
*/
private $project;
}
<?php
namespace Docker\ApiBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
*/
class Project
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\OneToMany(targetEntity="Source", mappedBy="project")
*/
private $sources;
public function __construct() {
$this->sources = new ArrayCollection();
}
public function getSources() {
return $this->sources;
}
}
So a many 'sources' can belong to one 'project'.
In my controller I have:
$em = $this->getDoctrine()->getManager();
$project = $em->find('Docker\ApiBundle\Entity\Project', 1);
$sources = $project->getSources()->toArray();
I have tried lots of things but I always get:
Notice: Undefined index: project in /.../www/vendor/doctrine/orm/lib/Doctrine/ORM/Persisters/BasicEntityPersister.php line 1577
Like I say, I know there are a lot of questions going around about this, but none of the accepted answers fix my problem.
This all looks pretty fundamental to using Doctrine2 so not sure what I am doing wrong - it could be something really obvious.
Any help would be appreciated.
You have:
/**
* #ORM\Column(type="integer")
* #ORM\ManyToOne(targetEntity="Project",inversedBy="sources")
* #ORM\JoinColumn(referencedColumnName="id")
*/
private $project;
Remove:
#ORM\Column(type="integer")
from annotation.
If this is exactly your code, i dont see a namespace in your Project class. Try adding the namespace line "namespace Docker\ApiBundle\Entity;".
If this is the same folder no need for "use" but if it s part of other bundle or folder try putting a line like "use Docker\ApiBundle\Entity\Project;"
in your Source class. I Hope it helps..
Otherwise :
<?php
namespace Azimut\ApiBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
*/
class Source
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
private $name;
/**
* #ORM\Column(type="integer")
* #ORM\ManyToOne(targetEntity="Azimut\ApiBundle\Entity\Project", inversedBy="sources")
* #ORM\JoinColumn(onDelete="CASCADE")
*/
private $project;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set project
*
* #param integer $project
* #return Source
*/
public function setProject($project)
{
$this->project = $project;
return $this;
}
/**
* Get project
*
* #return integer
*/
public function getProject()
{
return $this->project;
}
}
<?php
namespace Azimut\ApiBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* #ORM\Entity
*/
class Project
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\OneToMany(targetEntity="Azimut\ApiBundle\Entity\Source", mappedBy="object", cascade={"all"})
*/
private $sources;
public function __construct() {
$this->sources = new ArrayCollection();
}
public function getSources() {
return $this->sources;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Add sources
*
* #param \Azimut\ApiBundle\Entity\Source $sources
* #return Project
*/
public function addSource(\Azimut\ApiBundle\Entity\Source $sources)
{
$this->sources[] = $sources;
return $this;
}
/**
* Remove sources
*
* #param \Azimut\ApiBundle\Entity\Source $sources
*/
public function removeSource(\Azimut\ApiBundle\Entity\Source $sources)
{
$this->sources->removeElement($sources);
}
}
and little part of the controller:
public function helloAction()
{
$id = 1;
$em = $this->getDoctrine()->getManager();
$project = $em->getRepository('Azimut\ApiBundle\Entity\Project')->find($id);
$source1 = $em->getRepository('Azimut\ApiBundle\Entity\Source')->find(3);
$source2 = $em->getRepository('Azimut\ApiBundle\Entity\Source')->find(5);
$project->addSource($source1);
$sources = array();
$sources = $project->getSources();
var_dump($sources);
return ....
}
and this works just fine for me.

Symfony2, doctrine ManyToOne relationships error

I am trying to build a log of some action performed on some site using Symfony2 and Doctrine. I have 2 tables Sites and Logs. The Logs table will contain a siteid which is a foreign key to the id column of sites table. The Logs table can have multiple logs for same site.
When I try to insert an entry in the log table I get siteid is null error.
Here is my code:
Sites Entity:
<?php
namespace A\SHB\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Sites
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="A\SHB\Entity\SitesRepository")
*/
class Sites
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var ArrayCollection $siteLog
*
* #ORM\OneToMany(targetEntity="Logs", mappedBy="log", cascade={"persist"})
* #ORM\OrderBy({"siteid" = "ASC"})
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="log_id", referencedColumnName="siteid")
* })
*/
private $siteLog;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Constructor
*/
public function __construct()
{
$this->siteLog = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Add siteLog
*
* #param \A\SHB\Entity\SiteLog $siteLog
* #return Sites
*/
public function addSiteLog(\A\SHB\Entity\SiteLog $siteLog)
{
$this->siteLog[] = $siteLog;
return $this;
}
/**
* Remove siteLog
*
* #param \A\SHB\Entity\SiteLog $siteLog
*/
public function removeSiteLog(\A\SHB\Entity\SiteLog $siteLog)
{
$this->siteLog->removeElement($siteLog);
}
/**
* Get siteLog
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getSiteLog()
{
return $this->siteLog;
}
}
Logs Entity:
<?php
namespace A\SHB\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Logs
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="A\SHB\Entity\LogsRepository")
*/
class Logs
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var integer
*
* #ORM\Column(name="siteid", type="integer")
*/
private $siteid;
/**
* #var integer
*
* #ORM\Column(name="dateline", type="integer")
*/
private $dateline;
/**
* #var Log
*
* #ORM\ManyToOne(targetEntity="Sites")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="site_id", referencedColumnName="id")
* })
*/
private $log;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set siteid
*
* #param integer $siteid
* #return Logs
*/
public function setSiteid($siteid)
{
$this->siteid = $siteid;
return $this;
}
/**
* Get siteid
*
* #return integer
*/
public function getSiteid()
{
return $this->siteid;
}
/**
* Set dateline
*
* #param integer $dateline
* #return Logs
*/
public function setDateline($dateline)
{
$this->dateline = $dateline;
return $this;
}
/**
* Get dateline
*
* #return integer
*/
public function getDateline()
{
return $this->dateline;
}
/**
* Set log
*
* #param \A\SHB\Entity\Log $log
* #return Logs
*/
public function setLog(\A\SHB\Entity\Log $log = null)
{
$this->log = $log;
return $this;
}
/**
* Get log
*
* #return \A\SHB\Entity\Log
*/
public function getLog()
{
return $this->log;
}
}
Controller :
public function indexAction()
{
$sites = $this->getDoctrine()->getRepository('ASHB:Sites')->findAll();
foreach ($sites as $site)
{
$host = $site->getForum();
// Do something ....
$log = new Logs();
$log->setSiteid($site->getId());
$log->setDateline($temp['dateline']);
$em = $this->getDoctrine()->getManager();
$em->persist($log);
$em->flush();
}
return $this->render('ASHB:Default:index.html.twig', array('sites' => $output, 'counters' => $counters));
}
Now when I run this code, I get the following error:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'siteid' cannot be null"
If I var_dump $log, before $em->persist($log);, the siteid is there. I am not sure what is wrong and why the siteid is getting set to null.
Update 1:
I tried to make the following changes and still get the same error:
/**
* #var Log
*
* #ORM\ManyToOne(targetEntity="Sites", inversedBy="siteLog")
*/
private $log;
OneToMany doesn't need a JoinColumn. So it should look like, according to the documentation.
class Sites
{
/**
* #ORM\OneToMany(targetEntity="Logs", mappedBy="log")
*/
private $site_log;
}
class Logs
{
/**
* #ORM\ManyToOne(targetEntity="Sites", inversedBy="site_log")
* #ORM\JoinColumn(name="site_id", referencedColumnName="id")
*/
private $log;
}
orderBy and cascade were ignored for simplicity.
you have problem in your sturcture,
Remove this from Logs Entity
/**
* #var integer
*
* #ORM\Column(name="siteid", type="integer")
*/
private $siteid;
And then replace this part
/**
* #var Log
*
* #ORM\ManyToOne(targetEntity="Sites")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="site_id", referencedColumnName="id")
* })
*/
private $log;
with
/**
* #var Log
*
* #ORM\ManyToOne(targetEntity="Sites" inversedBy="logs")
*/
private $site;
And in your sites entity replace this with
/**
* #var ArrayCollection $siteLog
*
* #ORM\OneToMany(targetEntity="Logs", mappedBy="logs", cascade={"persist"})
* #ORM\OrderBy({"siteid" = "ASC"})
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="log_id", referencedColumnName="siteid")
* })
*/
private $logs;
with
/**
* #var ArrayCollection $siteLog
*
* #ORM\OneToMany(targetEntity="Logs", mappedBy="site", cascade={"persist"})
* #ORM\OrderBy({"siteid" = "ASC"})
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="log_id", referencedColumnName="id")
* })
*/
private $logs;
And then use proper setters and getters for these new feilds mean pass object to setter functions, for the class they are being mapped for(if you dont know this part write in comment i will do it as well)

Resources