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
Related
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
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
I'm trying to upload a file via vichuploader bundle on my Users entity.
Using hwioauthbundle that implements UserInterface, and i think the errors comes from that bundle...
So every time i try to uplod a file i got this exception :
Serialization of 'Symfony\Component\HttpFoundation\File\UploadedFile'
is not allowed
I already tried this solution but also same exception.
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use HWI\Bundle\OAuthBundle\OAuth\Response\UserResponseInterface;
use HWI\Bundle\OAuthBundle\Security\Core\User\FOSUBUserProvider as BaseClass;
use Symfony\Component\Security\Core\User\UserInterface;
use HWI\Bundle\OAuthBundle\Security\Core\User\OAuthUser;
/**
* Users
* #ORM\Table(name="users")
* #ORM\Entity(repositoryClass="AppBundle\Repository\UsersRepository")
*
*/
class Users extends OAuthUser
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var string
*
* #ORM\Column(name="first_name", type="string", length=255)
*/
private $firstName;
/**
* #var string
*
* #ORM\Column(name="last_name", type="string", length=255)
*/
private $lastName;
/**
* #var string
*
* #ORM\Column(name="civility", type="string", length=255, nullable=true)
*/
private $civility;
/**
* #var string
*
* #ORM\Column(name="avatar", type="string", length=255, nullable=true)
*/
private $avatar;
/**
* #var string
*
* #ORM\Column(name="qualification", type="string", length=255, nullable=true)
*/
private $qualification;
/**
* #var string
*
* #ORM\Column(name="level", type="string", length=255, nullable=true)
*/
private $level;
/**
* #var \DateTime
*
* #ORM\Column(name="birth_date", type="date", nullable=true)
*/
private $birthDate;
/**
* #var \DateTime
*
* #ORM\Column(name="hiring_date", type="date", nullable=true)
*/
private $hiringDate;
/**
* #var string
*
* #ORM\Column(name="country", type="string", length=255, nullable=true)
*/
private $country;
/**
* #var string
*
* #ORM\Column(name="city", type="string", length=255, nullable=true)
*/
private $city;
/**
* #var string
*
* #ORM\Column(name="linkedin_profil", type="string", length=255, nullable=true)
*/
private $linkedinProfil;
/**
* #var string
*
* #ORM\Column(name="web_site", type="string", length=255, nullable=true)
*/
private $webSite;
/**
* #var \DateTime
*
* #ORM\Column(name="date_last_cnx", type="datetimetz", nullable=true)
*/
private $dateLastCnx;
/**
*
* #ORM\OneToOne(targetEntity="AppBundle\Entity\Files",cascade={"persist"})
* #ORM\JoinColumn(name="file_id", referencedColumnName="id")
*/
public $cv;
/** #ORM\Column(name="google_id", type="string", length=255, nullable=true) */
private $google_id;
Files.php
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\HttpFoundation\File\File;
use Vich\UploaderBundle\Mapping\Annotation as Vich;
/**
* Files
* #Vich\Uploadable
* #ORM\Table(name="files")
* #ORM\Entity(repositoryClass="AppBundle\Repository\FilesRepository")
*/
class Files
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* NOTE: This is not a mapped field of entity metadata, just a simple property.
*
* #Vich\UploadableField(mapping="product_image", fileNameProperty="imageName", size="imageSize")
*
* #var File
*/
protected $imageFile;
/**
* #ORM\Column(type="string", length=255)
*
* #var string
*/
protected $imageName;
public function getId()
{
return $this->id;
}
/**
* If manually uploading a file (i.e. not using Symfony Form) ensure an instance
* of 'UploadedFile' is injected into this setter to trigger the update. If this
* bundle's configuration parameter 'inject_on_load' is set to 'true' this setter
* must be able to accept an instance of 'File' as the bundle will inject one here
* during Doctrine hydration.
*
* #param File|\Symfony\Component\HttpFoundation\File\UploadedFile $image
*
* #return Product
*/
public function setImageFile(File $image = null)
{
$this->imageFile = $image;
if ($image) {
// It is required that at least one field changes if you are using doctrine
// otherwise the event listeners won't be called and the file is lost
$this->updatedAt = new \DateTimeImmutable();
}
return $this;
}
/**
* #return File|null
*/
public function getImageFile()
{
return $this->imageFile;
}
/**
* #param string $imageName
*
* #return Product
*/
public function setImageName($imageName)
{
$this->imageName = $imageName;
return $this;
}
/**
* #return string|null
*/
public function getImageName()
{
return $this->imageName;
}
}
My form Userstype:
use AppBundle\Form\FilesType;
->add('cv',FilesType::class)
My form Filestype:
-> add('imageFile',
VichFileType::class, [
'required' => false,
'allow_delete' => true,
'download_link' => true,
'label' => false,
]);
You are serializing ImageFile entity within this code that's why you are getting the error , try removing that and add updatedAt field so that doctrine can track changes on the entity:
/**
* Files
* #ORM\Table(name="files")
* #ORM\Entity(repositoryClass="AppBundle\Repository\FilesRepository")
* #Vich\Uploadable
*/
class Files implements \Serializable
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* NOTE: This is not a mapped field of entity metadata, just a simple property.
*
* #Vich\UploadableField(mapping="product_image", fileNameProperty="imageName", size="imageSize")
*
* #var File
*/
protected $imageFile;
/**
* #ORM\Column(type="string", length=255)
*
* #var string
*/
protected $imageName;
/**
* #ORM\Column(type="datetime")
*
* #var string
*/
protected $updatedAt;
public function getId()
{
return $this->id;
}
/**
* If manually uploading a file (i.e. not using Symfony Form) ensure an instance
* of 'UploadedFile' is injected into this setter to trigger the update. If this
* bundle's configuration parameter 'inject_on_load' is set to 'true' this setter
* must be able to accept an instance of 'File' as the bundle will inject one here
* during Doctrine hydration.
*
* #param File|\Symfony\Component\HttpFoundation\File\UploadedFile $image
*
* #return Product
*/
public function setImageFile(File $image = null)
{
$this->imageFile = $image;
if ($image) {
// It is required that at least one field changes if you are using doctrine
// otherwise the event listeners won't be called and the file is lost
$this->updatedAt = new \DateTimeImmutable();
}
return $this;
}
/**
* #return File|null
*/
public function getImageFile()
{
return $this->imageFile;
}
/**
* #param string $imageName
*
* #return Product
*/
public function setImageName($imageName)
{
$this->imageName = $imageName;
return $this;
}
/**
* #return string|null
*/
public function getImageName()
{
return $this->imageName;
}
/** #see \Serializable::serialize() */
public function serialize()
{
return serialize(array(
$this->id,
$this->imageName,
));
}
/** #see \Serializable::unserialize() */
public function unserialize($serialized)
{
list (
$this->id,
) = unserialize($serialized);
}
/**
* #return string
*/
public function getUpdatedAt()
{
return $this->updatedAt;
}
/**
* #param string $updatedAt
*/
public function setUpdatedAt($updatedAt)
{
$this->updatedAt = $updatedAt;
}
}
for Symfony5
Class User implement UserInterface
public function __serialize(): array
{
return [
'id' => $this->id,
'email' => $this->email,
//......
];
}
public function __unserialize(array $serialized): User
{
$this->id = $serialized['id'];
$this->email = $serialized['email'];
// .....
return $this;
}
Check this out, one of your Users's relation has an UploadedFile property, which is essentially a File aka a filestream which aren't allowed to be serialized. Therefore you need to specify what you want to serialized:
https://symfony.com/doc/3.3/security/entity_provider.html
Basically you only neeed to serialized id, username and password (three is an example code on the above page)
Im tying to add communication parts to a rootCommunication in my data-fixture, there is no error, but only just NULL in the database field 'root_communication_id'. Why?
Parts of my Model 'Communication'
/**
* Communication
*
* #ORM\Table(name="communication")
* #ORM\Entity(repositoryClass="Mother\BaseBundle\Entity\Repository\CommunicationRepository")
*/
class Communication
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="message", type="text", nullable=true)
*/
private $message;
/**
* #ORM\ManyToOne(targetEntity="Communication", inversedBy="childrenCommunication", cascade={"persist"})
* #ORM\JoinColumn(name="root_communication_id", referencedColumnName="id", nullable=true)
*
*/
private $rootCommunication;
/**
* #ORM\OneToMany(targetEntity="Communication", mappedBy="rootCommunication")
*
*/
private $childrenCommunication;
}
In a first data-fixture i added three communications to the database, in this secound fixture i add the childrenCommunication to the rootCommunication.
/**
* {#inheritDoc}
*/
public function load( ObjectManager $manager ){
$contentRepo = $this->container->get('doctrine')->getManager()->getRepository('MotherBaseBundle:Communication');
$communication1 = $contentRepo->find( $this->getReference('communication1')->getId() );
$communication1->addChildrenCommunication( $this->getReference('communication2') );
$communication1->addChildrenCommunication( $this->getReference('communication3') );
$manager->persist( $communication1 );
$manager->flush();
}
I assume you are not setting the rootCommunication when you are adding the child.
You should add an auto setter to the add method, like..
public function addChildrenCommunication(CommunicationInterface $communication)
{
if (!$this->childrenCommunication->contains($communication)) {
$this->childrenCommunication->add($communication);
$communication->setRootCommunication($this);
}
return $this;
}
.. and the same for the remove..
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)