Persist twice on faker with nexest version - symfony

I have a problem on fixtures with fzaninotto/faker on a symfony project, i have some table with relations ManyToOne who not complete automaticaly when I load fixtures since i have update bundles on composer.
There is an error and a message who tell me to add cascad persist but if i do that the entry is create twice. The is my code and my error message, sorry for my bad english...
Project entity:
<?php
namespace App\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Symfony\Component\Security\Core\User\UserInterface;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass="App\Repository\UserRepository")
* #ORM\Table(name="`user`");
*/
class User implements UserInterface, \Serializable
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=100, nullable=true)
*/
private $firstname;
/**
* #ORM\Column(type="string", length=100, nullable=true)
*/
private $lastname;
/**
* #ORM\ManyToOne(targetEntity="App\Entity\Role")
* #ORM\JoinColumn(nullable=false)
*/
private $role;
Role Entity:
<?php
namespace App\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass="App\Repository\RoleRepository")
*/
class Role
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=100, unique=true)
*/
private $name;
/**
* #ORM\Column(type="string", length=100, unique=true)
*/
private $code;
/**
* #ORM\OneToMany(targetEntity="App\Entity\User", mappedBy="role")
*/
private $users;
Fixtures file:
<?php
namespace App\DataFixtures;
use Faker\Factory;
use App\Entity\Tag;
use App\Entity\Role;
use App\Entity\User;
use App\Entity\Skill;
use App\Entity\Follow;
use App\Entity\Statut;
use App\Entity\Techno;
use App\Entity\Comment;
use App\Entity\Project;
use App\Entity\Request;
use App\DataFixtures\Provider;
use Faker\ORM\Doctrine\Populator;
use Doctrine\Bundle\FixturesBundle\Fixture;
use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
class AppFixtures extends Fixture
{
public function load(ObjectManager $manager)
{
$generator = Factory::create('fr_FR');
// Ajout provider custom Provider
$generator->addProvider(new Provider($generator));
$populator = new Populator($generator, $manager);
// REMPLIT LES TABLES SIMPLES
// table "role"
$populator->addEntity(
Role::class,
2,
[
'name' => function () use ($generator) {
return $generator->unique()->randomElement(['Administrateur', 'Utilisateur']);
}
]
);
// table "user"
$populator->addEntity(
User::class,
10,
[
'firstname' => function () use ($generator) {
return ($generator->firstName());
},
'lastname' => function () use ($generator) {
return ($generator->lastName());
},
]
);
And my error message when i load fixtures:
In ORMInvalidArgumentException.php line 105:
Multiple non-persisted new entities were found through the given association graph:
* A new entity was found through the relationship 'App\Entity\User#role' that was not configured to cascade persist operations
for entity: Administrateur. To solve this issue: Either explicitly call EntityManager#persist() on this unknown entity or conf
igure cascade persist this association in the mapping for example #ManyToOne(..,cascade={"persist"}).
* A new entity was found through the relationship 'App\Entity\User#role' that was not configured to cascade persist operations
for entity: Utilisateur. To solve this issue: Either explicitly call EntityManager#persist() on this unknown entity or configu
re cascade persist this association in the mapping for example #ManyToOne(..,cascade={"persist"}).

Same issue with 1.9 version, so just downgrade :
1/ Remove faker folder in vendor.
2/ Change composer.json from
"fzaninotto/faker": "^1.9"
to
"fzaninotto/faker": "1.8"
3/ Run composer update
--> Breath now...

Related

No identifier/primary key specified for Entity why using KNP Translatable

I am using Knp/DoctrineBehaviors to translate my database content.
I followed the manual and created 2 entities, 1 for non-translatable content and the other for translatable fields.
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Knp\DoctrineBehaviors\Contract\Entity\TranslatableInterface;
use Knp\DoctrineBehaviors\Model\Translatable\TranslatableTrait;
/**
* Class Test
* #package App\Entity
* #ORM\Entity()
*/
class Test implements TranslatableInterface
{
use TranslatableTrait;
/**
* #var integer
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
* #ORM\Id()
*/
private $id;
/**
* #return int
*/
public function getId(): int
{
return $this->id;
}
/**
* #param int $id
*/
public function setId(int $id): void
{
$this->id = $id;
}
}
and the Translation entity:
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Knp\DoctrineBehaviors\Contract\Entity\TranslationInterface;
use Knp\DoctrineBehaviors\Model\Translatable\TranslationTrait;
/**
* Class TestTranslation
* #package App\Entity
* #ORM\Entity()
*/
class TestTranslation implements TranslationInterface
{
use TranslationTrait;
/**
* #var
* #ORM\Column(type="string")
*/
private $name;
/**
* #return mixed
*/
public function getName()
{
return $this->name;
}
/**
* #param mixed $name
*/
public function setName($name): void
{
$this->name = $name;
}
}
I also added the Bundle in my bundles.php file.
But when I run the command php bin/console doctrine:schema:update --force to create the table in give the error: No identifier/primary key specified for Entity "App\Entity\TestTranslation". Every Entity must have an identifier/p rimary key.
A primary key is missing in your entity "TestTranslation".
In doctrine every entity class must have an identifier/primary key. You can select the field that serves as the identifier with the #Id() annotation or in your case : #ORM\Id().
For example, add this to your entity :
/**
* #var integer
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
* #ORM\Id()
*/
private $id;
And then, you can play the command: php bin/console d:s:u --force
In my case, Symfony 3.4, I forgot to register the bundle and set the config.yml as:
knp_doctrine_behaviors:
translatable: true

symfony 2.8 generated crud controller with errors

I try generate CRUD controllers for my entities.
For example I wanna generate CRUD controller for AppBundle\Entity\User\User:
namespace AppBundle\Entity\User;
use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
use FOS\UserBundle\Model\Group;
/**
* #ORM\Entity
* #ORM\Table(name="user")
*/
class User extends BaseUser
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
public function __construct()
{
parent::__construct();
// your own logic
}
}
Generate entities:
$ app/console generate:doctrine:entities AppBundle
Generate crud:
$ app/console doctrine:generate:crud --entity=AppBundle:User\User
This command generete follow controller:
class UserController extends Controller
{
/**
* Lists all User\User entities.
*
* #Route("/", name="user_user_index")
* #Method("GET")
*/
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$user\Users = $em->getRepository('AppBundle:User\User')->findAll();
return $this->render('user/user/index.html.twig', array(
'user\Users' => $user\Users,
));
}
/**
* Finds and displays a User\User entity.
*
* #Route("/{id}", name="user_user_show")
* #Method("GET")
*/
public function showAction(User $user\User)
{
return $this->render('user/user/show.html.twig', array(
'user\User' => $user\User,
));
}
}
What the $user\Users? Symfony 2.8!
Maybe I can't use more directories in the Entity folder?
if you used the same namespace in your CRUD generation command as you have in this question, I expect that symfony is getting confused.
you have used:
AppBundle\Entity\User\User
note the extra \User.
If this isnt a typo, your entity should reside in the base Entity directory. The unusual path has probably confused it.
One would have thought however, that the generate command should have validated the string first.

Symfony2 OnetoOne relations

I have two class, User and PersonalData. We need relation OnetoOne with Doctrine in Symfony2. In my code I tried this relations, but in MySQL doesnt appear the foreign key.
My code:
namespace TFC\UserBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* User
*/
/** #ORM\Entity */
class User
{
/**
* #Id #Column(type="integer") #GeneratedValue
*/
private $id;
/**
* #var string
*/
private $email;
}
use Doctrine\ORM\Mapping as ORM;
/**
* PersonalData
*/
/** #ORM\Entity */
class PersonalData
{
/** #Id #OneToOne(targetEntity="User") */
private $userId;
/**
* #var string
*/
private $firstName;
}
You have to prefix with #ORM all your annotations like this:
#ORM\Id
#ORM\Column(type="integer")
#ORM\GeneratedValue(strategy="AUTO")
This "Unidirectional association" needs to be placed on User entity (because I think you want to load that informations from the User object...) and you don't need to care about the foreign key because doctrine create it automatically.
So place a $personalData property on User Entity and apply there the association, then delete $userId from PersonalData and add the $id property like did in User.
Even if the documentation claims that is not necessary have you tried something like:
#JoinColumn(name="userId", referencedColumnName="id")
When you generate the entity do you get any message?

Symfony2 Relationships using Interfaces results in duplicated table

I'm trying to relate an entity in one bundle with another in another bundle to make the second one independent from the first one, and be able to reuse it.
I'm following this documentation and this StackOverflows answer.
In the reusable bundle I have a Folder, File a that belongs to the folder and and interface like this:
namespace Acme\FolderBundle\Entity;
/**
* #ORM\Entity
*/
class Folder implements FolderInterface
{
// Has many files
}
namespace Acme\FolderBundle\Entity;
interface FolderInterface
{
// no methods here
}
namespace Acme\FolderBundle\Entity;
/**
* #ORM\Entity
*/
class File
{
// Belongs to one folder
}
And on the other bundle just one class:
namespace Acme\NewBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Acme\FolderBundle\Entity\Folder as BaseFolder;
use Acme\FolderBundle\Entity\FolderInterface;
/**
* #ORM\Entity
*/
class Folder extends BaseFolder implements FolderInterface
{
// Has many files
}
And the config.yml's ORM configuration:
orm:
auto_generate_proxy_classes: %kernel.debug%
auto_mapping: true
resolve_target_entities:
Acme\FolderBundle\Entity\FolderInterface: Acme\NewBundle\Entity\Folder
If I try to update my database schema, I get the following error:
[Doctrine\DBAL\Schema\SchemaException]
The table with name 'foldersDatabase.folder' already exists.
To get this working, I have to explicitly change one of the Folder's Entities table:
namespace Acme\FolderBundle\Entity;
/**
* #ORM\Entity
* #ORM\Table(name="distributed_folder")
*/
class Folder implements FolderInterface
{
// Has many files
}
Then, everything works but I get stuck with a table in my database (distributed_folder) that is never used.
Thanks a lot in advance!!
EDIT:
Fixed the annotation in the FolderInterface
You can not make one entity extend another entity this way.
If you want to have an abstract class which contains the fields for two or more subclass entities, you should mark the abstract class as #ORM\MappedSuperclass , and make sure, it will not have the annotation #Entity. While on the subclasses , they each should have #Entity annotation , and #Table annotation with a unique name attribute.
Here is an example :
<?php
namespace Radsphere\MissionBundle\Model\Core\BaseAbstract;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\MappedSuperclass
*
* An abstract class implementation of mission
*/
abstract class AbstractMission implements MissionInterface, IntegratedPluginInterface
{
/**
* #ORM\Id()
* #ORM\Column(name="id", type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\Column(type="string", length=36, unique=true)
*/
protected $guid;
/**
* #ORM\Column(type="string", length=255)
*/
protected $title;
/**
* #ORM\ManyToMany(targetEntity="MissionTask", cascade={"persist", "remove"})
* #ORM\JoinTable(name="mtm_mission_task",
* joinColumns={#ORM\JoinColumn(name="mission_id", referencedColumnName="id", onDelete="CASCADE")},
* inverseJoinColumns={#ORM\JoinColumn(name="task_id", referencedColumnName="id", onDelete="CASCADE")}
* )
*/
protected $tasks;
/**
* {#inheritDoc}
*/
public function addTask(MissionTaskInterface $missionTask)
{
$this->getTasks()->add($missionTask);
$missionTask->setMission($this);
}
/**
* {#inheritDoc}
*/
public function setTasks(Collection $tasks)
{
/** #var MissionTaskInterface $task */
foreach ($tasks as $task) {
$task->setMission($this);
}
$this->tasks = $tasks;
}
/**
* {#inheritDoc}
*/
public function getTasks()
{
$tasks = $this->tasks;
foreach ($tasks as $task) {
if ($task instanceof MissionTaskInterface) {
if (!$task->getIsEnabled()) {
/** #var $tasks Collection */
$tasks->removeElement($task);
}
}
}
return $tasks;
}
}
and the entity itself:
<?php
namespace Radsphere\MissionBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Radsphere\MissionBundle\Model\Core\BaseAbstract\AbstractMission;
/**
* Mission entity
*
* #ORM\Table(name="mission_bundle_mission", indexes={#ORM\Index(name="guid_idx", columns={"guid"})})
* #ORM\HasLifecycleCallbacks
* #ORM\Entity(repositoryClass="MissionRepository")
*/
class Mission extends AbstractMission
{
/**
* Constructor
*/
public function __construct()
{
$this->tasks = new ArrayCollection();
}
}

how to extend an entity from one bundle to another bundle

i have an already created symfony bundle. i wanted to add another bundle for my application separately. so now im facing a problem that how to extend an entity from old bundle to newly created one. i extended it normally but it giving errors.
i have these 2 bundles,
MyFirstBundle
MySecondBundle
MyFirstBundle entity,
namespace My\FirstBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
*
* #ORM\Table(name="companies")
* #ORM\Entity
* #ORM\HasLifecycleCallbacks
*/
class Company
{
/**
* #var integer $id
*
* #ORM\Column(name="id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*
* #Groups({"list_companies", "company_details", "ad_details"})
*/
private $id;
/**
* #ORM\Column(name="name", type="string", length=50, nullable=true)'
*
* #Groups({"ad_details"})
*/
private $name;
MySecondBundle Entity,
namespace My\SecondBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use My\FirstBundle\Entity\Company as BaseCompany;
class Companies extends BaseCompany
{
public function __construct() {
parent::__construct();
}
}
im not sure that i can extend my entity like this. im getting error when creating forms with this entity
Class "MySecondBundle:companies" seems not to be a managed Doctrine entity. Did you forget to map it?
You need to add the doctrine annotations for the second entity as well.
/**
*
* #ORM\Table(name="companies")
* #ORM\Entity
* #ORM\HasLifecycleCallbacks
*/
class Companies extends BaseCompany
{
public function __construct() {
parent::__construct();
}
}

Resources