Trending queries

Generating a single Entity from existing database using symfony2 and doctrine

Is it possible to generate a single entity from database using the Symfony2 console tool?

In the middle of coding I had to add a table and there are modifications made to the existing entity classes. So I don't want all my entities regenerated.

Any suggestions will be appreciated!

Doctrine - How to print out the real sql, not just the prepared statement?

We're using Doctrine, a PHP ORM. I am creating a query like this:

$q = Doctrine_Query::create()->select('id')->from('MyTable');

and then in the function I'm adding in various where clauses and things as appropriate, like this

$q->where('normalisedname = ? OR name = ?', array($string, $originalString));

Later on, before execute()-ing that query object, I want to print out the raw SQL in order to examine it, and do this:

$q->getSQLQuery();

However that only prints out the prepared statement, not the full query. I want to see what it is sending to the MySQL, but instead it is printing out a prepared statement, including ?'s. Is there some way to see the 'full' query?

cascade={"remove"} VS orphanRemoval=true VS ondelete="CASCADE

I tried to gather some information about the following way to delete automatically child entity when a parent entity is deleted. Seems that the most common way is to use one those three annotation: cascade={"remove"} OR orphanRemoval=true OR ondelete="CASCADE".

I am a bit confused about the third one: ondelete="CASCADE", as the explanation in doctrine official documentation about this one are very scarce) and I would love if someone could confirm me the following information I gathered and understand from my research on the net and experience...

What does it do?

cascade={"remove"} ==> the entity on the inverse side is deleted when the owning side entity is. Even if you are in a ManyToMany with other owning side entity.

  • should be used on collection (so in OneToMany or ManyToMany relationship)
  • implementation in the ORM

orphanRemoval=true ==> the entity on the inverse side is deleted when the owning side entity is AND it is not connected to any other owning side entity anymore. (ref. doctrine official_doc

  • implementation in the ORM
  • can be used with OneToOne, OneToMany or ManyToMany

onDelete="CASCADE" ==> this will add On Delete Cascade to the foreign key column in the database

  • This strategy is a bit tricky to get right but can be very powerful and fast. (ref. doctrine official_doc ... but haven't read more explanations)
  • ORM has to do less work (compared to the two previous ways of doing it) and therefore should have better performance.

other information

  • all those 3 ways of doing are implemented on bidirectional relationship entities (right???)
  • using cascade={"remove"} completely by-passes any foreign key onDelete=CASCADE. (ref. doctrine_official_doc)

EXAMPLE ON HOW TO USE IT IN CODE

  • orphanRemoval and cascade={"remove"} are defined in the inversed entity class.
  • ondelete="CASCADE" is defined in the owner entity
  • you can also just write @ORM\JoinColumn(onDelete="CASCADE") and let doctrine handle the column names

cascade={"remove"}

/**
* @OneToMany(targetEntity="Phonenumber", mappedBy="contact", cascade={"remove"})
*/
protected $Phonenumbers

orphanRemoval=true

/**
* @OneToMany(targetEntity="Phonenumber", mappedBy="contact", orphanRemoval=true)
*/
protected $Phonenumbers

onDelete="CASCADE"

/** 
* @ManyToOne(targetEntity="Contact", inversedBy="phonenumbers")
* @JoinColumn(name="contact_id", referencedColumnName="contact_id", onDelete="CASCADE")
*/ 
protected $contact; 
Order by multiple columns with Doctrine

I need to order data by two columns (when the rows have different values for column number 1, order by it; otherwise, order by column number 2)

I'm using a QueryBuilder to create the query.

If I call the orderBy method a second time, it replaces any previously specified orderings.

I can pass two columns as the first parameter:

->orderBy('r.firstColumn, r.secondColumn', 'DESC');

But I cannot pass two ordering directions for the second parameter, so when I execute this query the first column is ordered in an ascending direction and the second one, descending. I would like to use descending for both of them.

Is there a way to do this using QueryBuilder? Do I need to use DQL?

How do I delete an entity from symfony2

My first symfony2 project is a list of guests (invited in an event) stored in a database. I have

  • created the entity class Guest with all variables for them (id, name, address, phone number etc.)
  • created the schema in the mysql db
  • created a route for "adding a guest" to a twig template
  • created a formType

and finally a "createGuest" method in the Controller and everything works fine.

I can't manage to remove a guest from the database. I have read every tutorial in the web, including the official Symfony2 book; all that it says is :

Deleting an Object

Deleting an object is very similar, but requires a call to the remove() method of the entity manager:

$em->remove($product);
$em->flush();

It does not say anything more than that (even the "Update an object" section is missing documentation) on how to connect the controller deleteAction($id) with the twig template. What I want to do is to list all guests with a viewGuests action and a viewGuests twig template, having a delete icon next to every row, which you should click to delete an entry. Simple, but I cannot find any documentation and do not know where to start from.

public function deleteGuestAction($id)
    {
        $em = $this->getDoctrine()->getEntityManager();
        $guest = $em->getRepository('GuestBundle:Guest')->find($id);

        if (!$guest) {
            throw $this->createNotFoundException('No guest found for id '.$id);
        }

        $em->remove($guest);
        $em->flush();

        return $this->redirect($this->generateUrl('GuestBundle:Page:viewGuests.html.twig'));
    }
How to use andWhere and orWhere in Doctrine?
WHERE a = 1 AND (b = 1 Or b = 2) AND (c = 1 OR c = 2)

How can i make this in Doctrine?

$q->where("a = 1");
$q->andWhere("b = 1")
$q->orWhere("b = 2")
$q->andWhere("c = 1")
$q->orWhere("d = 2")

this isnt correctly... Should be:

$q->where("a = 1");
$q->andWhere("b = 1")
   $q->orWhere("b = 2")
$q->andWhere("c = 1")
   $q->orWhere("d = 2")

but how can i make it? In Propel is function getNewCriterion, and in Doctrine...?

Doctrine: cascade="remove" vs orphanRemoval=true

What is the difference between the 2 options above? When is it preferable to choose each option?

What is Doctrine hydration?

I've read about hydration in doctrine's documentation but I still can't understand what it is.

Could someone please explain?

PHPUnit Mock Objects and Static Methods

I am looking for the best way to go about testing the following static method (specifically using a Doctrine Model):

class Model_User extends Doctrine_Record
{
    public static function create($userData)
    {
        $newUser = new self();
        $newUser->fromArray($userData);
        $newUser->save();
    }
}

Ideally, I would use a mock object to ensure that fromArray (with the supplied user data) and save were called, but that's not possible as the method is static.

Any suggestions?

Doctrine 2 Inheritance Mapping with Association

NOTE : if what I want is not possible, a "not possible" answer will be accepted

In the Doctrine 2 documentation about inheritance mapping, it says there are 2 ways :

  • Single table inheritance (STI)
  • Class table inheritance (CTI)

For both, there is the warning :

If you use a STI/CTI entity as a many-to-one or one-to-one entity you should never use one of the classes at the upper levels of the inheritance hierachy as “targetEntity”, only those that have no subclasses. Otherwise Doctrine CANNOT create proxy instances of this entity and will ALWAYS load the entity eagerly.

So, how can I proceed to use inheritance with an association to the base (abstract) class ? (and keep the performance of course)


Example

A user has many Pet (abstract class extended by Dog or Cat).

What I want to do :

class User {
    /**
     * @var array(Pet) (array of Dog or Cat)
     */
    private $pets;
}

Because of the warning in Doctrine documentation, I should do that :

class User {
    /**
     * @var array(Dog)
     */
    private $dogs;
    /**
     * @var array(Cat)
     */
    private $cats;
}

This is annoying, because I loose the benefits of inheritance !

Note : I didn't add the Doctrine annotations for the mapping to DB, but you can understand what I mean

Is there a built-in way to get all of the changed/updated fields in a Doctrine 2 entity

Let's suppose I retrieve an entity $e and modify its state with setters:

$e->setFoo('a');
$e->setBar('b');

Is there any possibility to retrieve an array of fields that have been changed?

In case of my example I'd like to retrieve foo => a, bar => b as a result

PS: yes, I know I can modify all the accessors and implement this feature manually, but I'm looking for some handy way of doing this

Get the last insert id with doctrine 2?

How can I get the last insert id with doctrine 2 ORM? I didn't find this in the documentation of doctrine, is this even possible?

How to re-save the entity as another row in Doctrine 2

Let's say I have entity $e. Is there any generic way to store it as another row, which would have the same entity data but another primary key?

Why I need this: I'm implementing some sort of Temporal Database schema and instead of updating the row I just need to create another one.

PHP ORMs: Doctrine vs. Propel

I'm starting a new project with symfony which is readily integrated with Doctrine and Propel, but I of course need to make a choice.... I was wondering if more experienced people out there have general pros and/or cons for going with either of these two?

Thanks a lot.

EDIT: Thanks for the all the responses, useful stuff. There's no truly correct answer to this question so I'll just mark as approved the one that got the most popular up-votes.

Doctrine 2 can't use nullable=false in manyToOne relation?

An User has one Package associated with it. Many users can refer to the same package. User cannot exists without a Package defined. User should own the relation. Relation is bidirectional, so a Package has zero or more users in it.

These requirements lead to ManyToOne relation for User and OneToMany relation of Package in Doctrine 2. However package_id in user table (that is foreign-key) allows null values. I've tried setting nullable=false but command:

 php app/console doctrine:generate:entities DL --path="src" --no-backup

Says that there is no attribute nullable for the relation ManyToOne. What i'm missing?

class User
{

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

    /**
     * @ORM\ManyToOne(targetEntity="Package", inversedBy="users")
     */
    private $package;

}

class Package
{

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

    /**
     * @ORM\OneToMany(targetEntity="User", mappedBy="package")
     */
    private $users;

}
Symfony2: how to get all entities of one type which are marked with "EDIT" ACL permission?

Can someone tell me how to get all entities of one type which are marked with "EDIT" ACL permission?

I would like to build a query with the Doctrine EntityManager.

Explicitly set Id with Doctrine when using "AUTO" strategy

My entity uses this annotation for it's ID:

/**
 * @orm:Id
 * @orm:Column(type="integer")
 * @orm:GeneratedValue(strategy="AUTO")
 */
protected $id;

From a clean database, I'm importing in existing records from an older database and trying to keep the same IDs. Then, when adding new records, I want MySQL to auto-increment the ID column as usual.

Unfortunately, it appears Doctrine2 completely ignores the specified ID.


New Solution

Per recommendations below, the following is the preferred solution:

$this->em->persist($entity);

$metadata = $this->em->getClassMetaData(get_class($entity));
$metadata->setIdGeneratorType(\Doctrine\ORM\Mapping\ClassMetadata::GENERATOR_TYPE_NONE);
$metadata->setIdGenerator(new \Doctrine\ORM\Id\AssignedGenerator());

Old Solution

Because Doctrine pivots off of the ClassMetaData for determining the generator strategy, it has to be modified after managing the entity in the EntityManager:

$this->em->persist($entity);

$metadata = $this->em->getClassMetaData(get_class($entity));
$metadata->setIdGeneratorType(\Doctrine\ORM\Mapping\ClassMetadata::GENERATOR_TYPE_NONE);

$this->em->flush();

I just tested this on MySQL and it worked as expected, meaning Entities with a custom ID were stored with that ID, while those without an ID specified used the lastGeneratedId() + 1.

Understanding Doctrine Cascade Operations

I want to check my understanding of cascade operations on Doctrine associations. For the purpose of this question, I have two models: Customer and Insuree.

If I define a many to many relationship between a Customer and Insuree and set cascade{"all"}, I understand that this will:

  • Adding a new insuree to a customer will persist this insuree and create an association in the join table.
  • Removing an insuree from the collection will detach the insuree from the customer and detach the customer from the insuree.
  • Deleting the customer will delete all insurees associated with the customer.

This is the definition of the association on Customers.

/**
 * @ORM\ManyToMany(targetEntity="Insuree", inversedBy="customers", cascade={"all"})
 * @ORM\JoinTable(name="customer_insuree",
 *      joinColumns={@ORM\JoinColumn(name="customer_id", referencedColumnName="id")},
 *      inverseJoinColumns={@ORM\JoinColumn(name="insuree_id", referencedColumnName="id")}
 * )
 */
protected $insurees;

If I define the inverse many to many relationship between an Insuree and Customer and set cascade{"all"}, I understand that this will:

  • Adding a new customer to an insuree will persist this customer and create an association in the join table.
  • Removing a customer from the collection will detach the customer from the insuree and detach the insuree from the customer.
  • Deleting the insuree will delete all customers associated with it.

This is the definition of the association on Insurees.

/**
 * @ORM\ManyToMany(targetEntity="Customer", mappedBy="insurees", cascade={"all"})
 */
protected $customers;

If I then define the relationship as to cascade on persist, merge and detach - deleting the insuree will not delete all associated customers - it will only remove the associations between the insuree and its customers?

/**
 * @ORM\ManyToMany(targetEntity="Customer", mappedBy="insurees", cascade={"persist", "merge", "detach"})
 */
protected $customers;
How to specify null value as filter in a Doctrine query?

I am using Doctrine 1.1 in Zend. I am trying to write a query that will return records that have a null value in a certain column.

    $q = Doctrine_Query::create()
    ->select('a.*')
    ->from('RuleSet a')
    ->where('a.vertical_id = ?', null);

    $ruleset_names_result = $q->execute(array(), Doctrine::HYDRATE_ARRAY);

I have three records in the ruleset table which have a NULL value in the vertical_id column yet the query doest not find these.

Appreciate the help.

Sid.

Difference between ObjectManager and EntityManager in Symfony2?

What's the difference between Doctrine\Common\Persistence\ObjectManager and Doctrine\ORM\EntityManager when using it in a custom form type?

I can get the respository using both $this->em->getRepository() and $this->om->getRepository().

class MyFormType extends \Symfony\Component\Form\AbstractType
{

    /**
     * @var Doctrine\ORM\EntityManager
     */
    protected $em;

    public function __construct(Doctrine\ORM\EntityManager $em)
    {
        $this->em = $em;
    }

 }

Instead of:

class MyFormType extends \Symfony\Component\Form\AbstractType
{

    /**
     * @var Doctrine\Common\Persistence\ObjectManager
     */
    protected $om;

    public function __construct(Doctrine\Common\Persistence\ObjectManager $om)
    {
        $this->om = $om;
    }

 }
Doctrine2: Best way to handle many-to-many with extra columns in reference table

I'm wondering what's the best, the cleanest and the most simply way to work with many-to-many relations in Doctrine2.

Let's assume that we've got an album like Master of Puppets by Metallica with several tracks. But please note the fact that one track might appears in more that one album, like Battery by Metallica does - three albums are featuring this track.

So what I need is many-to-many relationship between albums and tracks, using third table with some additional columns (like position of the track in specified album). Actually I have to use, as Doctrine's documentation suggests, a double one-to-many relation to achieve that functionality.

/** @Entity() */
class Album {
    /** @Id @Column(type="integer") */
    protected $id;

    /** @Column() */
    protected $title;

    /** @OneToMany(targetEntity="AlbumTrackReference", mappedBy="album") */
    protected $tracklist;

    public function __construct() {
        $this->tracklist = new \Doctrine\Common\Collections\ArrayCollection();
    }

    public function getTitle() {
        return $this->title;
    }

    public function getTracklist() {
        return $this->tracklist->toArray();
    }
}

/** @Entity() */
class Track {
    /** @Id @Column(type="integer") */
    protected $id;

    /** @Column() */
    protected $title;

    /** @Column(type="time") */
    protected $duration;

    /** @OneToMany(targetEntity="AlbumTrackReference", mappedBy="track") */
    protected $albumsFeaturingThisTrack; // btw: any idea how to name this relation? :)

    public function getTitle() {
        return $this->title;
    }

    public function getDuration() {
        return $this->duration;
    }
}

/** @Entity() */
class AlbumTrackReference {
    /** @Id @Column(type="integer") */
    protected $id;

    /** @ManyToOne(targetEntity="Album", inversedBy="tracklist") */
    protected $album;

    /** @ManyToOne(targetEntity="Track", inversedBy="albumsFeaturingThisTrack") */
    protected $track;

    /** @Column(type="integer") */
    protected $position;

    /** @Column(type="boolean") */
    protected $isPromoted;

    public function getPosition() {
        return $this->position;
    }

    public function isPromoted() {
        return $this->isPromoted;
    }

    public function getAlbum() {
        return $this->album;
    }

    public function getTrack() {
        return $this->track;
    }
}

Sample data:

             Album
+----+--------------------------+
| id | title                    |
+----+--------------------------+
|  1 | Master of Puppets        |
|  2 | The Metallica Collection |
+----+--------------------------+

               Track
+----+----------------------+----------+
| id | title                | duration |
+----+----------------------+----------+
|  1 | Battery              | 00:05:13 |
|  2 | Nothing Else Matters | 00:06:29 |
|  3 | Damage Inc.          | 00:05:33 |
+----+----------------------+----------+

              AlbumTrackReference
+----+----------+----------+----------+------------+
| id | album_id | track_id | position | isPromoted |
+----+----------+----------+----------+------------+
|  1 |        1 |        2 |        2 |          1 |
|  2 |        1 |        3 |        1 |          0 |
|  3 |        1 |        1 |        3 |          0 |
|  4 |        2 |        2 |        1 |          0 |
+----+----------+----------+----------+------------+

Now I can display a list of albums and tracks associated to them:

$dql = '
    SELECT   a, tl, t
    FROM     Entity\Album a
    JOIN     a.tracklist tl
    JOIN     tl.track t
    ORDER BY tl.position ASC
';

$albums = $em->createQuery($dql)->getResult();

foreach ($albums as $album) {
    echo $album->getTitle() . PHP_EOL;

    foreach ($album->getTracklist() as $track) {
        echo sprintf("\t#%d - %-20s (%s) %s\n", 
            $track->getPosition(),
            $track->getTrack()->getTitle(),
            $track->getTrack()->getDuration()->format('H:i:s'),
            $track->isPromoted() ? ' - PROMOTED!' : ''
        );
    }   
}

The results are what I'm expecting, ie: a list of albums with their tracks in appropriate order and promoted ones being marked as promoted.

The Metallica Collection
    #1 - Nothing Else Matters (00:06:29) 
Master of Puppets
    #1 - Damage Inc.          (00:05:33) 
    #2 - Nothing Else Matters (00:06:29)  - PROMOTED!
    #3 - Battery              (00:05:13) 

So what's wrong?

This code demonstrates what's wrong:

foreach ($album->getTracklist() as $track) {
    echo $track->getTrack()->getTitle();
}

Album::getTracklist() returns an array of AlbumTrackReference objects instead of Track objects. I can't create proxy methods cause what if both, Album and Track would have getTitle() method? I could do some extra processing within Album::getTracklist() method but what's the most simply way to do that? Am I forced do write something like that?

public function getTracklist() {
    $tracklist = array();

    foreach ($this->tracklist as $key => $trackReference) {
        $tracklist[$key] = $trackReference->getTrack();

        $tracklist[$key]->setPosition($trackReference->getPosition());
        $tracklist[$key]->setPromoted($trackReference->isPromoted());
    }

    return $tracklist;
}

// And some extra getters/setters in Track class

EDIT

@beberlei suggested to use proxy methods:

class AlbumTrackReference {
    public function getTitle() {
        return $this->getTrack()->getTitle()
    }
}

That would be a good idea but I'm using that "reference object" from both sides: $album->getTracklist()[12]->getTitle() and $track->getAlbums()[1]->getTitle(), so getTitle() method should return different data based on the context of invocation.

I would have to do something like:

 getTracklist() {
     foreach ($this->tracklist as $trackRef) { $trackRef->setContext($this); }
 }

 // ....

 getAlbums() {
     foreach ($this->tracklist as $trackRef) { $trackRef->setContext($this); }
 }

 // ...

 AlbumTrackRef::getTitle() {
      return $this->{$this->context}->getTitle();
 }

And that's not a very clean way.

Best way to create a test database and load fixtures on Symfony 2 WebTestCase?

I have a WebTestCase that executes some basic routes in my application.

I want to, on the setUp method of PHPUnit, create a test database identical to my main database, and load fixtures into it.

I'm currently doing some workaround and executing some console commands, something like this:

class FixturesWebTestCase extends WebTestCase
{
    protected static $application;

    protected function setUp()
    {
        self::runCommand('doctrine:database:create');
        self::runCommand('doctrine:schema:update --force');
        self::runCommand('doctrine:fixtures:load --purge-with-truncate');
    }

    protected static function runCommand($command)
    {
        $command = sprintf('%s --quiet', $command);

        return self::getApplication()->run(new StringInput($command));
    }

    protected static function getApplication()
    {
        if (null === self::$application) {
            $client = static::createClient();

            self::$application = new Application($client->getKernel());
            self::$application->setAutoExit(false);
        }

        return self::$application;
    }
}

But I'm quite sure this is not the best approach, especially because the doctrine:fixtures:load expects the user to hit a Y char to confirm the action.

How can I solve that?

Deprecation: Doctrine\ORM\Mapping\UnderscoreNamingStrategy without making it number aware is deprecated

I'm using Symfony 4.3.8 and I can't find any information about thoses deprecations :

User Deprecated: Creating Doctrine\ORM\Mapping\UnderscoreNamingStrategy without making it number aware is deprecated and will be removed in Doctrine ORM 3.0.

Creating Doctrine\ORM\Mapping\UnderscoreNamingStrategy without making it number aware is deprecated and will be removed in Doctrine ORM 3.0.

I searched in stacktrace and found this :

class UnderscoreNamingStrategy implements NamingStrategy
{
private const DEFAULT_PATTERN      = '/(?<=[a-z])([A-Z])/';
private const NUMBER_AWARE_PATTERN = '/(?<=[a-z0-9])([A-Z])/';

/**
 * Underscore naming strategy construct.
 *
 * @param int $case CASE_LOWER | CASE_UPPER
 */
public function __construct($case = CASE_LOWER, bool $numberAware = false)
{
    if (! $numberAware) {
        @trigger_error(
            'Creating ' . self::class . ' without making it number aware is deprecated and will be removed in Doctrine ORM 3.0.',
            E_USER_DEPRECATED
        );
    }

    $this->case    = $case;
    $this->pattern = $numberAware ? self::NUMBER_AWARE_PATTERN : self::DEFAULT_PATTERN;
}

In this class, the constructor is always called without params, so $numberAware is always false.

This class is called in file which has been auto generated by the Symfony Dependency Injection, so I can't "edit" it ...

I thought maybe it was in doctrine.yaml :

doctrine:
orm:
    auto_generate_proxy_classes: true
    naming_strategy: doctrine.orm.naming_strategy.underscore
    auto_mapping: true
    mappings:
        App:
            is_bundle: false
            type: annotation
            dir: '%kernel.project_dir%/src/Entity'
            prefix: 'App\Entity'
            alias: App

But I have not found any option to allow the number aware :(

Doctrine 2: Update query with query builder

Hi I've got the following query but it doesn't seem to work.

$q = $this->em->createQueryBuilder()
    ->update('models\User', 'u')
    ->set('u.username', $username)
    ->set('u.email', $email)
    ->where('u.id = ?1')
    ->setParameter(1, $editId)
    ->getQuery();
$p = $q->execute();

This returns the following error message:

Fatal error: Uncaught exception 'Doctrine\ORM\Query\QueryException' with message '[Semantical Error] line 0, col 38 near 'testusername WHERE': Error: 'testusername' is not defined.' in ...

I would be glad of any help

Doctrine 2 OneToMany Cascade SET NULL

The error

Cannot delete or update a parent row: a foreign key constraint fails.

The classes

class Teacher {

    /**
     *@ORM\OneToMany(targetEntity="publication", mappedBy="teacher")
     */
    protected $publications;
}

class Publication {

    /**
     * @ORM\ManyToOne(targetEntity="Teacher", inversedBy="publications")
     * @ORM\JoinColumn(name="teacher_id", referencedColumnName="id")
     */
    protected $teacher;
}

I want

What I want is to make it that when you delete a teacher, the id_teacher is modified to NULL. I want to keep the publication but without reference to Professor.

I don't know how do that in Doctrine, Is it possible? Or always the relationship has to be with a teacher?

Execute raw SQL using Doctrine 2

I want to execute raw SQL using Doctrine 2

I need to truncate the database tables and initialize tables with default test data.

How to encode Doctrine entities to JSON in Symfony 2.0 AJAX application?

I'm developing game app and using Symfony 2.0. I have many AJAX requests to the backend. And more responses is converting entity to JSON. For example:

class DefaultController extends Controller
{           
    public function launchAction()
    {   
        $user = $this->getDoctrine()
                     ->getRepository('UserBundle:User')                
                     ->find($id);

        // encode user to json format
        $userDataAsJson = $this->encodeUserDataToJson($user);
        return array(
            'userDataAsJson' => $userDataAsJson
        );            
    }

    private function encodeUserDataToJson(User $user)
    {
        $userData = array(
            'id' => $user->getId(),
            'profile' => array(
                'nickname' => $user->getProfile()->getNickname()
            )
        );

        $jsonEncoder = new JsonEncoder();        
        return $jsonEncoder->encode($userData, $format = 'json');
    }
}

And all my controllers do the same thing: get an entity and encode some of its fields to JSON. I know that I can use normalizers and encode all entitities. But what if an entity has cycled links to other entity? Or the entities graph is very big? Do you have any suggestions?

I think about some encoding schema for entities... or using NormalizableInterface to avoid cycling..,

Checking for duplicate keys with Doctrine 2

Is there an easy way to check for duplicate keys with Doctrine 2 before doing a flush?

Symfony2 Use Doctrine in Service Container

How do I use Doctrine in a service container?

The Code just causes an error message "Fatal error: Call to undefined method ...::get()".

<?php

namespace ...\Service;

use Doctrine\ORM\EntityManager;
use ...\Entity\Header;

class dsdsf
{ 
    protected $em;

    public function __construct(EntityManager $em)
    {
        $this->em = $em;
    }

    public function create()
    {
        $id = 10;
        $em = $this->get('doctrine')->getEntityManager();
        $em->getRepository('...')->find($id);
    }
}

services.yml

service:
    site:
        class: ...\Service\Site
Doctrine - A new entity was found through the relationship

since 2 weeks, we are having this problem while trying to flush new elements:

CRITICAL: Doctrine\ORM\ORMInvalidArgumentException:

A new entity was found through the relationship 'Comment#capture' that was not configured to cascade persist operations for entity

But the capture is already in the database, and we are getting it by a findOneBy, so if we cascade persist it, or persist it, we get a

Table constraint violation: duplicate entry.

The comments are created in a loop with differents captures, with a new, and all required field are set.

With all of the entities persisted and / or got by a findOne (and all valid), the flush still fails.

I'm on this issue since a while, so please help me

doctrine