FAQ Database Discussion Community


Symfony2 & Doctrine: Optimizing Query (Fetching EAGER)

php,symfony2,doctrine,dql
Currently my query looks like this: $customers = $em->createQueryBuilder() ->select('c') ->from('AppBundle:Customer', 'c') ->orderBy('c.id', 'ASC') ->setFirstResult($offset) ->setMaxResults($max) ->getQuery() ->getResult(); This returns me all data of the Customer entity. However, in my Twig template I have to access the @ManyToMany relation that the Customer entity has with PhoneNumber. That causes an extra...

Set methods between relationships in Symfony2

php,symfony2,doctrine
I have 2 Entities - Users and Projects. The relationship between them looks like this: // Acme/MyBundle/Entity/Project.php ... /** * @ORM\ManyToOne(targetEntity="User", inversedBy="projects") * @ORM\JoinColumn(name="author_id", referencedColumnName="id") */ private $author; public function setAuthor(\Acme\MyBundle\Entity\User $author = null) { $this->author = $author; return $this; } ... other set/get methods... and // Acme/MyBundle/Entity/User.php ... /**...

Symfony2 - Entity Collection Choice Restriction

php,symfony2,doctrine,entity,twig
I have the following setup: Entity: Customer Entity: Account Entity: Message Now imagine the following problem: The account 'Mark' is in charge of two customers, 'Ben' and 'Lili'. The account 'Tim' is in charge of two other customers, 'Tom' and 'Ronny'. The account 'Ben' now wants to send a message...

Mapping Nested Tree With Doctrine 2 and YAML

doctrine2,tree,doctrine,yaml
We are currently working on implementing a nested tree using the DoctrineExtensions module. We believe we have wired everything up correctly, however when we go to flush using Doctrine, we keep getting an Exception. SyntaxErrorException in AbstractMySQLDriver.php line 90: An exception occurred while executing 'INSERT INTO ProductTree (left, right, rootProductTreeID,...

Symfony, security.yml “Unknown Entity namespace alias”

php,symfony2,doctrine2,doctrine
I would like to implement Symfony security into my project. Problem is I have to use two databases (one for admins, second for users). I have configured config.yml : orm: auto_generate_proxy_classes: %kernel.debug% default_entity_manager: default entity_managers: default: connection: system mappings: FinanceCmsBundle: ~ admin: connection: admin mappings: FinanceCzBundle: ~ and set my...

Symfony2 Inserting Error “Warning: spl_object_hash() expects parameter…”

php,symfony2,doctrine2,doctrine
when I try to persist my object and flush it I get this error message: Warning: spl_object_hash() expects parameter 1 to be object, integer given 500 Internal Server Error - ContextErrorException I know this kind of question has been posted a lot in stack overflow but it still couldn't solve...

query builder gives exeption

symfony2,doctrine,query-builder
i am using query builder like $querym =$querym->select('DISTINCT(a.id)') ->where ('a.doctorid =:u') ->setParameter('u', $u); $query =$query->select('DISTINCT(d.id),d.name,d.dob,d.mobile') ->innerJoin('d.PatientSymptoms','ps') ->innerJoin('ps.symptoms', 's') ->andWhere('ps.symptoms =:name') ->where($query->expr()->In('d.id', $querym)) ->setParameter('name', $name); gives me Error: Method Doctrine\Common\Collections\ArrayCollection::__toString() must not throw an exception is it possible to write it some...

MySQL Error on Persisting to Database Symfony2

php,mysql,symfony2,doctrine
Problem: I get the following MySQL error upon persisting an entity to database with doctrine, none of my Entity names are reserved words. I've tried numerous things including rebuilding the database and tables and running doctrine:schema:update but to no avail. Any help would be greatly appreciated. Error: string(601) "An exception...

A reference to the object element Symfony2

symfony2,doctrine,entity
I try to get to "content" from message entity. This is my dump($messages): http://s13.postimg.org/96ytd93vb/message.png and my code in controller: $em = $this->getDoctrine()->getEntityManager(); $messages = $em->getRepository('DashboardMainBundle:Message')->findBy( array( 'receiver'=> $UserId, 'id' => $Id ), array('createdAt' => 'ASC') ); How can I take "content" from this array in controller? It looks simple but...

Validate Doctrine entities with Symfony Validator

php,validation,symfony2,doctrine
I have difficulties integrating the Symfony validator component with Doctrine (standalone, not using the complete Symfony framework). So far I have managed to register the annotation contraints in Doctrine's AnnotationRegistry and hook into the lifecycle callbacks, but how would I actually retrieve a validator and parse the annotations in the...

Inheritance in Symfony2

symfony2,inheritance,doctrine
I've already had a diagram class in which I have ClassA (superClass) and two classes ClassB and ClassC which inherit from ClassA. How can I code them in Symfony2 using Doctrine? NB : When I'd generated entities with classical method (I mean with doctrine:generate:entity), I got three tables in my...

Doctrine “A new entity was found through the relationship” error

php,symfony2,doctrine2,doctrine
First off I want to say I've read through all the docs and googled this plenty before posting this question. I know what that error means (unpersisted entity in a relationship) I'm getting this error where I think I shouldn't be getting it. I have a OneToMany bi-directional relationship as...

Gedmo translatable / default locale and sonata admin bundle

symfony2,doctrine,sonata-admin,symfony-sonata
I am currently using the sonata admin bundle with the sonata translation bundle and gedmo translatable to localize my entities, which generally works nice. I have a category table with a field "title" which I'm localizing to a "category_translation" table. Now I can see, that the title in my default...

Symfony 2 - best approach for summing results of values in related entities

php,symfony2,doctrine
My code is aimed at getting items from database. Those item may have either debit values or credit values. In template I present all of the values but would like also to provide information about sum of debit and account values connected with the account ($account_id) What would be your...

How to join many to many in createQuery()

symfony2,join,doctrine,many-to-many,createquery
I'm working on my portfolio, and I got a page where I show my project. I created 2 cayegorie for now: Programmation and artistic. Each of my project can be a programming project, an artistique project or both. There for, I made a table project and a table categorie and...

Symfony time field not using the same date as the corresponding entity property

php,symfony2,datetime,doctrine2,doctrine
I've got an entity with a duration property, declared as time type: /* @ORM\Column(type="time") */ private $duration; In my Symfony form, this duration property maps to a time field: $builder->add( 'duration', 'time', [ 'input' => 'datetime', 'widget' => 'text' ] ) As the time type does not exist in PHP,...

Symfony ManyToMany delete record

php,symfony2,doctrine,many-to-many
I was trying to update a many to many relation between "book * <- -> * tag". For that, I first wanted to delete all current related tags of a book - to add afterwards again the changed /entered tags. Deleting all tags of a book is working, but when...

How to fetch related objects from second many-to-many relation?

php,symfony2,orm,doctrine
If there are three entities: Students, Classes and Topics, which are related as follows: Student <-> Class: many-to-many (a student attends multiple classes and a class is attended by multiple students) Class <-> Topic: many-to-many (a class covers multiple topics and a topic is covered in multiple classes) With Doctrine...

Is there a detailed comparison between Propel 2 and Doctrine 2

performance,orm,doctrine,comparison,propel
From the existing comparisons between 1.x versions of Propel and Doctrine, I couldn't decide whether to use Doctrine 2.x or Propel 2.x for my new project. I have some experience with Propel but am not happy with the way Propel 2 broke compatibility with previous versions. Hence this question. Is...

ZF2 Doctrine Query With Multiple OR Conditions

symfony2,doctrine2,doctrine,mariadb
I've wrote the following Doctrine query: $query3 = $this->entityManager ->createQueryBuilder() ->select('t.textDomain , t.translationKey , t.languageIso , t.translationDate') ->from( 'AMDatabase\Entity\TheVerse\TranslationsMasters', 't' ) ->groupBy('t.languageIso') ->orderBy( 't.translationDate', 'DESC' ); // the values of $key2 array are: // en-US // es-MX // es-PR foreach( $translation AS $key2=>$value2 ) { if ( $key2 == 'en-US'...

Getting a list of Doctrine Entities (UI population, access rights, etc.)

php,inheritance,orm,doctrine2,doctrine
I'm trying to get a hang of Doctrine Entities and their inheritance model. Here's a situation I'd like some advice on; I have a base class Box, and depending on the application, several other classes can extend the Box class (STI), such as: TextBox, ImageBox, SliderBox, etc. PortraitBox could extend...

Command line Doctrine ORM with Silex: You are missing a “cli-config.php” or “config/cli-config.php” file in your project

php,symfony2,doctrine,silex
I am trying to use Doctrine ORM with Silex, and finding it an altogether frustrating experience, due to the lack of consistent documentation. When I run vendor/bin/doctrine at the console, I get the following output: output: You are missing a "cli-config.php" or "config/cli-config.php" file in your project, which is required...

how to create virtual column on Doctrine Symfony2

symfony2,doctrine
how to create virtual column on Doctrine Symfony2 i have two table table Company --------------------------------- id | company_name | address --------------------------------- 1 | sample Co Ltd | NY 2 | company Co Ltd | LA --------------------------------- table Ships --------------------------------- id | company_id | ships_name --------------------------------- 1 | 1 | Ship...

How to detect if entity exist in database

symfony2,doctrine,entity-relationship
I have 2 entities, User and Profile. Profile has in-symfony relation with User, but there is no in-database relation (no foreign key, no cascade) - only simple int column named user_id and nothing more. Problem is obvious: when i delete user - associated profiles persists, but their user_id points to...

The class 'Doctrine\ORM\EntityManager' was not found in the chain configured namespaces XXX

php,doctrine2,zend-framework2,doctrine
I have read the the other questions concerning this issue but have not come across a solution as of yet. I get the following error message: The class 'Doctrine\ORM\EntityManager' was not found in the chain configured >namespaces ZfcUser\Entity, Common\Entity, Employment\Entity, Intern\Entity, >Team\Entity, PurchaseRequest\Entity. I have a HolidayEntity, HolidayController, HolidayService. Adding...

doctrine does not hydration when select custom fields

doctrine2,doctrine,doctrine-query
i have tried select fields with doctrine query buidler. $queryBuilder = $entityManager->createQueryBuilder(); $queryBuilder->select('au.id, au.firstName') ->from('Api\V1\Entity\AgencyUser', 'au') ->orderBy('au.firstName', 'asc'); $queryBuilder->andWhere('au.agency = :agencyId') ->setParameter('agencyId', $agency->getId()); print_r($queryBuilder->getQuery()->getResult(Query::HYDRATE_OBJECT));exit; result : Array ( [0] => Array ( [id] => 1 [firstName] => agency ) ) why this is an array ? i want to hydrated...

A kind of pivot table using Symfony2 and Doctrine

php,mysql,symfony2,doctrine,data-modeling
I'm developing a KPI management tool for application Quality services with Symfony, Doctrine and jQuery. I created three entities which are: Application (ID, Name, ...) KPI (ID, Name, Category, ...) Value (Application_ID, KPI_ID, Month, Value) so my value table has some values like: ID_APP | ID_Kpi | Month | Value...

Doctrine query condition doesn't work

symfony2,doctrine,twig
I'm using doctrine in my SYmfony2 project. I did a query that get all my project in a certain language, but it returns me all the language: public function rechercherProjets($lang, $cat) { return $qb = $this->createQueryBuilder('p') ->innerJoin ('p.descriptions', 'pi') ->innerJoin('p.categories', 'c') ->where('c.tag = :cat') ->andWhere('pi.langue = :lang') ->setParameters(array('lang'=>$lang,'cat'=>$cat)) ->getQuery()->getResult(); }...

Symfony2, how to display data from entities with ManyToMany associations

php,symfony2,doctrine,twig
I have multiple entities associated by ManyToMany and ManyToOne associations and I have problem with displaying data more than one level deep in to associations For example. There are 3 entities connected. Customer->Address->Country. In TWIG I can display: {{ customer.name }} // outputs name {{ customer.address.postcode }} // outputs post...

The file could not be found while using LifecycleCallbacks

php,symfony2,orm,doctrine,assert
I have problem with form validation in symfony2. In my case the $form->isValid() command results in The file could not be found. even though that I provide a file during filling in the form Additionally debuging of setFile function in documents entity leads to conclusion that file value is set...

Doctrine One to Many relationship

php,symfony2,doctrine2,doctrine,one-to-many
I got confuse in doctrine one to many relationship. Question 1: Correct me if I am wrong. I assume that when I try to $em = $this->getDoctrine()->getManager(); $product_repo = $em->getRepository('MyBundle:Product'); $products = $product_repo->findAll(); dump($products); I will see the related features attached to the $features variable, so when I use $products->getFeatures()...

Composer - Install github fork/branch

php,symfony2,doctrine,composer-php,doctrine-migrations
Why composer cant install branch from https://github.com/wimvds/DoctrineMigrationsBundle/tree/feature/multiple-em-support ? My composer.json: "repositories": [ { "type":"package", "package": { "name": "doctrine/doctrine-migrations-bundle", "version":"master", "source": { "url": "https://github.com/wimvds/DoctrineMigrationsBundle.git", "type": "git", "reference":"master" } } } ], "require": { (...) "doctrine/migrations": "1.0.*@dev", "doctrine/doctrine-migrations-bundle": "dev-feature/multiple-em-support", (...) }. Error: composer...

Symfony Doctrine fails to create foreign key

mysql,symfony2,doctrine,foreign-keys
Fields in table Ordertaxi: @ORM\Column(name="custom_id", type="integer", options={"unsigned"=true}) private $customId; // new "column", which i want to add @ORM\OneToOne(targetEntity="CustomOrder") private $custom; Field in table CustomOrder: @ORM\Column(name="id", type="integer") @ORM\Id @ORM\GeneratedValue(strategy="AUTO") private $id; Executing: php app/console doctrine:schema:update --dump-sql Getting: ALTER TABLE Ordertaxi ADD CONSTRAINT FK_D345B7FB614A603A FOREIGN KEY (custom_id) REFERENCES CustomOrder (id); CREATE UNIQUE...

Doctrine behavioral extensions: Loggable with Timestampable

symfony2,doctrine,doctrine-extensions
As I understand from the docs, you can get a full history of changes on an entity with Loggable as long as it is configured as \Versioned in the entity. I was wondering if this log history retains also a timestamp of the changes? If not, is it possible to...

How do I complete this andWhere Doctrine query?

php,doctrine2,doctrine
I'm assuming this is easy to do with Doctrine, however I have no clue how to do it. I'm sure I am missing something basic. Doctrine_Query::create() ->from('Product p') ->leftJoin('p.Category c' ) ->leftJoin('c.Image i') ->where('p.name LIKE ?', '%'.$search.'%'), which works, but I am trying to select the category and tried this,...

Symfony2 Undefined method. The method name must start with either findBy or findOneBy

php,class,symfony2,model-view-controller,doctrine
I am currently working with Symfony2's Part 4 OF The SymBlog project I am getting this ERROR message: Undefined method 'getLatestPosts'. The method name must start with either findBy or findOneBy!500 Internal Server Error - BadMethodCallException This is my PostRepository Class: <?php namespace BLog\BlogBundle\Entity; use Doctrine\ORM\EntityRepository; class PostRepository extends EntityRepository...

how to implement join to more than one table on same column in doctrine

doctrine2,doctrine,doctrine-query
My scenario is like this. item_master table item_id (primary key) | item_name -------------------------------------- 1 | Keyboard -------------------------------------- 2 | Mouse -------------------------------------- user_lp_requirement table id1 |item_id | otherColumns1 ----------------------- 1 | 1 | 1 ----------------------- 1 | 2 | 3 ----------------------- item_id is foreign key reference to item_master training_program table id2...

Compare dates between datetimes with Doctrine

php,symfony2,datetime,doctrine2,doctrine
I have a Syfmony2 app with a table which has a date field. This date field is datetime type. I need to get all the entities which the same date as now. But if I do: $now = new \DateTime(); $data = $entityRepository->findByDate($now); I get 0 results because doctrine is...

when flush() primary key does not get inserted

php,symfony2,doctrine
I am working on a PHP Project, utilizing Symfony 2, and Doctrine as ORM. When I persist and flush the object the primary key column is not even in the insert SQL DML Statement, and of course an error is thrown. The ID is a generated value, using PHP's uniqid....

Symfony2 and Doctrine $em->persist VS $em->merge

symfony2,merge,doctrine,persist
Hi there I've got a quick question regarding Doctrine and the difference between merge() and persist() I have a NewsBuilder class: This takes a News Entity and checks to see if it exists in the database, if it does it sets the values of the entity to the data passed...

In Symfony is there a way to access the app_dev information with REST

symfony2,doctrine
I am trying to optimize my app and have been using the profiler you get with app_dev to be very useful, especially the doctrine panel. Is there any way to log this information to a file so I can see what is happening when I POST / PUT to a...

Doctrine fetching indirectly associated objects

database,symfony2,doctrine,one-to-many,dql
I am trying to fetch associated objects through 3 tables (user, client, account). User has a one-to-many relationship to client, client has a one-to-many relationship to account. I easily fetch all the clients for one specific user using this simple code: $user = $this->getUser(); $id = $user->getId(); $user = $this->getDoctrine()->getRepository('AcmeUserBundle:User')->find($id);...

Unique Index when data already exists

php,symfony2,doctrine,migration,unique
I ran into troubles when I want to add new column mapped ONE TO ONE. It creates unique index on that column and while executing SQL it obviously fail, because that table already contains rows. It's not a problem to remove data in development database, but it will be in...

Symfony 2 and Doctrine. Delete parent on table inheritance

symfony2,doctrine2,doctrine
I have the following structure: /** * @ORM\Entity * @ORM\HasLifecycleCallbacks() * @ORM\InheritanceType("JOINED") * @ORM\DiscriminatorColumn(name="discr", type="string") * @ORM\DiscriminatorMap({"notice" = "UserNoticeNotification", "change_shift" = "ChangeShiftRequestNotification", "change_watch" = "ChangeWatchRequestNotification"}) */ class Notification { /** * @ORM\Entity * @ORM\HasLifecycleCallbacks() * @ORM\Table(name="notification_user_notice") */ class UserNoticeNotification extends Notification { /** *...

Fosuserbundle register validation not work

php,symfony2,doctrine,fosuserbundle
When I register with an existing email, in the registerAction RegisterController $form->isValid() returns true despite that there is a constraint that exists in Fosuserbundle but I got an DBALException (An exception occurred while executing 'INSERT INTO … '). I created a bundle that inherits FOSUserBundle and MyUser entity inherits BaseUser...

Search from comma separated values in column

sql,postgresql,doctrine2,doctrine
I have a table with 2 coloums - id and pets pets column contain abbreviated pet names separated by , [comma] as shown below +----+-------------+ | id | pets | +----+-------------+ | 1 | CAT,DOG | +----+-------------+ | 2 | CAT,DOG,TIG | +----+-------------+ | 3 | ZEB,MOU | +----+-------------+ Now...

why is Doctrine creating one big migration?

php,symfony2,doctrine2,doctrine,migration
I have a couple entities that I created: User namespace App\Models; use Doctrine\ORM\Mapping as ORM; use Symfony\Component\Validator\Constraints as Assert; /** * @ORM\Entity * @ORM\Table(name="users") */ class User { /** * @ORM\Id * @ORM\Column(type="integer") * @ORM\GeneratedValue */ protected $id; /** * @ORM\Column(type="string", length=32, nullable=false) */ protected $firstName; /** * @ORM\Column(type="string", length=32,...

Symfony2 / Doctrine2 : How to override DebugStack class used in doctrine DataCollector?

php,symfony2,doctrine2,doctrine,override
In order to better manage how I was making my database calls using Doctrine, I investigated how I could add the php debug_backtrace to the symfony doctrine db collector. I managed to identify the modifications I had to make but I did not yet found a good way to override...

Attempted to call method “getDoctrine” on class (Symfony)

php,mysql,symfony2,doctrine2,doctrine
I am trying to create small application to read the record from the table by id using symfony/doctrine. My steps: Created controller (GS\OrderBunndle\Controller\CustomerCuntroller.php), route. Testing URL - it is working; Creating Entity for customer table (GS\OrderBundle\Entity\Customer.php) with columns and getters/setters; 3) Created GS\OrderBundle\Entity\CustomerRepository.php (I am not sure why do I...

Symfony 2.6, pull in other bundle repository, container aware to fixtures

php,symfony2,doctrine,symfony-2.6
I am trying to pull in data from another bundles entity repository in a data fixtures file, to do this i am trying to implement container aware but its not working, is there any way i can run a query on another bundles entity repository from inside a data fixtures...

Laravel (Eloquent) Table || Peer equivalent

php,laravel,doctrine,eloquent,propel
Propel uses Peer classes, and doctrine used Table classes as a way to manipulate respective objects and object properties, without having to pollute the actual object with static methods. After cursory glance of the laravel (eloquent) docs, I didn't see anything that eloquent provides for the same Peer or Table...

Symfony does not remove Element from ArrayCollection

symfony2,controller,doctrine,arraycollection
i want to remove an role from the roles-ArrayCollection in the User Entity. User and Role have an M:N connection. In my Controller: $em = $this->getDoctrine()->getManager(); $user = $em->getRepository('UserBundle:User')->find($userId); $user->removeRole($roleID); $em->flush(); If I execute the controller, there are no error messages. But the Role is still assigned to the user....

Automatically filter out rows that don't meet a condition in Doctrine

php,symfony2,doctrine2,doctrine,doctrine-1.2
I have a database already in use and I can't really change it. On this database I use a "soft delete": instead of actually deleting a record, I just modify a flag (e.g. setting del=1). I don't use the GEDMO template (SoftDelete) but I want the same functionality. Currently when...

Error running doctrine:fixtures:load in heroku

symfony2,heroku,doctrine
I deploy a symfony application to heroku. When I try to run the command: heroku run php app/console doctrine:fixtures:load I get the error: [InvalidArgumentException] There are no commands defined in the "doctrine:fixtures" namespace. Did you mean one of these? doctrine:database doctrine:generate doctrine:query doctrine:schema doctrine:mapping doctrine:cache doctrine Everything else seems to...

Symfony 2 - Entity has to be managed or scheduled for removal for single computation

php,symfony2,doctrine
When I am submitting symfony2 form I got the following error: Entity has to be managed or scheduled for removal for single computation What does this error mean? I am using the form which is aimed at adding new item to DB. I have multiple ManyToOne relations in the form....

Query Builder with join and condition in Many to many relation

php,symfony2,doctrine2,doctrine,symfony-2.3
I have a many to many relation with Employee and MembreFamille. And i want to get all MembreFamilles that have an Employee. This is my query : class MembreFamilleRepository extends EntityRepository { public function getMembres($emp) { $qb = $this->createQueryBuilder('a'); $qb ->leftJoin('a.employees', 'employees'); $qb ->where('employees.id = :id') ->setParameter('id', $emp); return $qb...

MongoDB+Doctrine: How to sort the query by text search score

php,mongodb,doctrine,full-text-search
I have a code like this that searches by the text index: $expr = $queryBuilder->expr()->operator('$text', ['$search' => $this->value]); $result = $queryBuilder->equals($expr)->getQuery()->execute(); But the result is not sorted by the relevance, which I want. I found some info here but could not figure out how to add field score to search...

Doctrine connection with db

php,sql-server,symfony2,doctrine2,doctrine
I am about to start a project in doctrine symfony, but I have to make connection with multiple databases. One of them is an existing database (SQL SERVER) that cannot be mapped with ORM. Is there any possibility to connect with this db with another db that is NOT mapped...

How to save additional entity while persisting another in Doctrine?

symfony2,orm,doctrine2,doctrine
I've got a Place entity and a Distance one, like so: class Place { /** @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** @ORM\Column(type="string", length=62, nullable=false) */ private $name; /** @ORM\OneToMany(targetEntity="Distance", mappedBy="origin") */ protected $distancesTo; /** @ORM\OneToMany(targetEntity="Distance", mappedBy="destination") */ protected $distancesFrom; } class Distance { /** @ORM\Id @ORM\Column(type="integer") @ORM\GeneratedValue(strategy="AUTO") */ private...

Doctrine doesn't find the rows just flushed

symfony2,doctrine2,doctrine
I have 3 entities: Subjects, Sections, Questions. Everyone has relations with the rest. I am trying to get the questions of the current $user. If there are none, I make a copy of the default ones with user = NULL. But Doctrine gives me headaches. Initially it wouldn't get questions...

Installing Sylius with eZ Publish 5

symfony2,doctrine,composer-php,sylius,ezpublish
I have problems installing Sylius Bundle. Here is the error when i try to access the web site or when i try to update composer : [RuntimeException] "Cannot find Doctrine RTEL" Here is my config : composer.json "doctrine/orm": "~2.3", "friendsofsymfony/user-bundle": "2.0.*@dev", "sylius/money-bundle": "0.12", "sylius/order-bundle": "0.12", "sylius/product-bundle": "0.12", "sylius/resource-bundle": "0.12", "sylius/cart-bundle":...

Infinite loop in Doctrine event listener when trying to save additional entity

php,symfony2,orm,doctrine2,doctrine
I want that every time a new Distance entity (from Place_A to Place_B) is saved, the reverse distance (from Place_B to Place_A) gets inserted too into the DB. My problem is the following listener loops infinitely (hence the counter): class Listener { public $count; public function prePersist(LifecycleEventArgs $eventArgs) { if...

Symfony2 persist not working from my controller

symfony2,doctrine,entities,persist
I am new with symfony and I've been trying for several days to implement a multiple image upload. I use entity Image and entity CollecImages with a oneToMany relation. I managed to do so thanks to this article. So now I can upload an image collection and i can see...

[Symfony 2]Use Doctrine into a service

xml,symfony2,doctrine2,doctrine
I've created a new service in my project. This service is configured in XML. I'd like to user the EntityManager, to retreive som data in the service but I'm not able to «connect» Doctrine to my service. Currently, I have this code: services.xml <service id="SiteService.search" class="Site\ProductBundle\Search\SphinxSearch" factory-service="doctrine.orm.entity_manager" factory-method="getRepository"> <argument>Site\ProductBundle\Entity\Product</argument> </service>...

ID not saved in OneToMany relationship

symfony2,doctrine,one-to-many
I'm working on a project using Symfony2. But I'm running into a problem. I have an entity Purchase and another, TypePurchase. They have an OneToMany-relationship, but when I look inside of the table of TypePurchase, the Purchase entity ID is not saved. It's value is null. I already tried $types->setPurchase($this)...

silex loop one sql statement over another one

mysql,symfony2,doctrine,twig,silex
I have to get team members by their groups from a database. My Database looks like: table team_groups: id name table team_member: id name description imagepath team_group_id I have an twig template where the team_members are shown by there groups like this: <div class="row row-centered"> <h3 class="text-center">{{team_group.name}}</h3> <div class="col-xs-6 col-centered...

Can and Should I cache symfony2 getUser()

symfony2,doctrine,fosuserbundle
I am using Symfony ( current version 2.6.4 ) whenever I want to check if a user is loggedin ( I am also using FOSUserBundle ) I use $user = $this->getUser(); in my controller which works out just fine but if I open 10 links in 1 second this query...

Error: Call to a member function on array

symfony2,doctrine
I'm trying to get the products from my selection in the Category object but I gives me the following error Error: Call to a member function getProducts() on array in /Users/jurrejan/Documents/projects/audsur2/src/Audsur/ShopBundle/Controller/DefaultController.php line 94 Where am I going wrong? The object has multiple products array(1) { [0]=> object(stdClass)#329 (6) { ["__CLASS__"]=>...

Should I clear/warm symfony2 cache after doctrine migrations?

symfony2,caching,doctrine,capifony
I would like to know about how symfony2 console commands cache:clear and cache:warmup works in regards to changes in doctrine entities. I've read this http://blog.whiteoctober.co.uk/2014/02/25/symfony2-cache-warmup-explained/ and this http://stackoverflow.com/a/17787070/779320. There it is stated that symfony2 warm-up generates Doctrine proxies. Thing is, I frequently have a situation after application deploy using capifony...

Symfony2 AnnotationException You have to enable OPCache or ZendOptimizer

symfony2,doctrine2,annotations,doctrine,opcache
I have application based on the Symfony2 framework. I have moved to the production environment, website was running fine (I was trying to adjust caching - on my hosting is xcache). But suddenly I has this error: Fatal error: Uncaught exception 'Doctrine\Common\Annotations\AnnotationException' with message 'You have to enable opcache.save_comments=1 or...

Doctrine PHPCR @Children & @Child

doctrine,symfony-cmf,doctrine-phpcr
I started learning PHPCR with doctrine in Symfony-CMF, and I have a question. Is that possible to have @Children and @Child on 2 differents attributes of the same document ? According to the doc... The annotated instance variable will be populated with Documents directly below the instance variables document class...

Sorting a collection in doctrine2

php,mongodb,doctrine2,doctrine,odm
I've written the following query (that may or may not be efficient, I'm still a newbie): $collection = $this->dm->getConnection()->selectCollection('db_name', 'collection_name'); $query = array('array_name' => new \MongoId(id)); $cursor = $collection->find($query)->limit(9)->sort('r', 'desc'); I'm trying to sort by an r value that looks like this in the document: "r": 0.58325652219355106354 but it isn't...

Database/Code solutions for model with dynamic data, using Symfony 2 with Doctrine

database,symfony2,model,doctrine,nosql
I'm making an application with Symfony2 and Doctrine and i'm facing a problem i've always wondered about but it's never been an issue until today: How to handle dynamic data? In the application i'm developing there will be some data that might be relational and to which a relational database...

Remove automaticaly entity in BD when choice value not selected (or null selected)

php,forms,symfony2,doctrine
I would like to know if symfony/doctrine can manage automaticaly the fact that instead of setting the value of my entity to null it could symply remove it. (by removing it I mean the records where the value equal null) exemple: I have a PICTURE entity linked to a VOTE...

How to select all rows that don't have one-to-many entity with certain value using Doctrine

php,mysql,orm,doctrine2,doctrine
I have two entities: Cage and Bird. Cage has Birds inside so their relationship is one-to-many. Bird has a field name. How can I select all Cages where there's no Bird with name eagle inside. I was trying to do this: $cages = $this->createQueryBuilder("c") ->leftJoin("c.birds", "b") ->where("b.name != :name") ->setParameter("name",...

what is wrong in this statement php doctrine

php,doctrine2,doctrine,php-5.3
I'm trying make a validation in my db using doctrine where I just need to make this statement in SQL like, Select * from usuarios where usuario_email = someEmail After I click the submit button from my form, I instantiate the class UsuarioDao, from a script that includes bootstrap.php (from...

doctrine/migrations incompatible with symfony 2.2.*

php,symfony2,doctrine2,doctrine
long story short: Im using Symfony 2.2.* (yes, its old) and a DEV-Enviroment using a deploy script. This script runs "composer update". Every thing works fine until today. Now I recive this error: - Conclusion: remove symfony/symfony v2.2.11 - Conclusion: don't install symfony/symfony v2.2.11 - Conclusion: don't install symfony/symfony v2.2.10...

Doctrine migrations table collation

php,symfony2,doctrine2,doctrine
Trying to find a way to programatically create tables with certain collation, but can't seem to find a way how to do it properly. I am using the "doctrine/doctrine-migrations-bundle": "2.1.*@dev" and Symfony 2.3, I set up in my config.yml: # Doctrine Configuration doctrine: dbal: driver: "%database_driver%" host: "%database_host%" port: "%database_port%"...

Doctrine, editing ManyToMany - Indirect modification of overloaded property

php,orm,doctrine,many-to-many
lets suppose I have something like this class Menu extends \Kdyby\Doctrine\Entities\BaseEntity { /** * @ORM\ManyToMany(targetEntity="MenuItem", mappedBy="menus") **/ protected $menuItems; function __construct() { $this->menuItems = new \Doctrine\Common\Collections\ArrayCollection(); } } and this class MenuItem extends \Kdyby\Doctrine\Entities\BaseEntity { /** * @ORM\ManyToMany(targetEntity="Menu", inversedBy="menuItems") * @ORM\JoinTable(name="cms_menuMenuItems") */ protected $menus; public function __construct() { $this->menus =...

JMSSerializerBundle, Deserialize doesn't Relationship After Persist

php,symfony2,doctrine,deserialization,jmsserializerbundle
Deserialization process OneToMany-ManyToOne process always get relation data sets NULL. The Result Entity: @ORM\OneToMany(targetEntity="\Acme\DemoBundle\Entity\AnswerContent", mappedBy="answerResult", cascade={"persist", "remove"}, orphanRemoval=true) @JMS\Type("ArrayCollection<Acme\DemoBundle\Entity\AnswerContent>") @JMS\Groups({"survey_answer_fetching"}) The Answer Entity: @ORM\ManyToOne(targetEntity="Acme\DemoBundle\Entity\AnswerResult", inversedBy="answers") @ORM\JoinColumn(name="answer_result_id",...

Trigger Slug with symfony

symfony2,doctrine,slug
I am working with Symfony, and I am trying to slug some element of my database using Doctrine's extension Gedmo. The issue is that I initialize my database with a sql script, so I dont trigger the generation of the slug by Doctrine. I would like to know if there...

Create small page to display content of the table with Symfony and Doctrine

php,mysql,symfony2,doctrine2,doctrine
I am trying to create simple page to display content of the table (customer: id, first_name, last_name) with Symfony + doctrine. I created GS\OrderBundle\Entity\Customer with columns and getters/setters. Created route for it. I want to create a view , something like: <table> {% for c in form %} {% set...

I am getting this error while debugging [duplicate]

php,doctrine
This question already has an answer here: PHP Parse/Syntax Errors; and How to solve them? 10 answers Parse error: syntax error, unexpected '->' (T_OBJECT_OPERATOR) in C:\xampp\htdocs\evnxt\evnxt\vendor\evnxt\Admin.php on line 25 line 24 : $qb = $entityManager->createQueryBuilder(); line 25 : $qb->select('f')->from('Fest', 'f')->where('f.dateTime >:date')->setMaxResults(10)->setParameter('date', time()); line 26 : $qb->orderBy('f.dateTime', 'ASC');->setFirstResult($page); line 27...

Doctrine isn't saving my entities?

php,symfony2,doctrine2,doctrine
I have the following model, or as you call them entity, and I also have a controller, everything works in this action, but when I check the database there is no user. So I am curious as what I am missing. So lets start at the beginning as to what...

symfony1 doctrine form submit - where to inject logic

php,forms,doctrine,symfony1,symfony-1.4
I've got a simple form that includes an input that will take money, i.e. float. So far it can accept a well-formed decimal only, e.g. 12768.56. The task to inject some server-side logic (no javascript here) that would intercept the input value, like 12 768,56, replace it with 12768.56 and...

Doctrine mapped field is not working

php,doctrine
I have two entities User\User and Misc\Notification and I want to have the possibility to fetch the user's notifications inside the User entity, by doing $user->getNotifications(). Usually I have no problem with this type of relations. See my code below (I just added the TicketApp relation as an example, since...

Symfony 2 - Class “Mingle\StandardBundle\Entity\Product” is not a valid entity or mapped superclass

php,symfony2,doctrine,entity,bundle
I created a Product.php file in my bundle Mingle\StandardBundle\Entity like this: <?php namespace Mingle\StandardBundle\Entity; use Doctrine\ORM\Mapping as ORM; /* * @ORM\Entity * @ORM\Table(name="product") */ class Product { /* * @ORM\Column(type="integer") * @ORM\ID * @ORM\GeneratedValue(strategy="AUTO") */ protected $id; /* * @ORM\Column(type="string",length=100) */ protected $name; /* * @ORM\Column(type="decimal",scale=2) */ protected $price; /*...

DoctrineODM Priming of Multi-Level References

mongodb,symfony2,doctrine,doctrine-odm
Sorry for the awkward title but I have no better naming for the issue (comments on how to properly name the question are welcome). Let's say I have 3 Documents: Category Product Version A Category has many Products. A Product has many Versions. Now I want to Query for all...

Do you have to register your custom validators in symfony

php,validation,symfony2,doctrine,custom-validators
I was reading the documentation on making custom validators and It doesn't state that you have to register custom created validators, but what else would cause this issue? I created a custom constraint: namespace Lib\Validators\UniqueValidator\Constraint; use Symfony\Component\Validator\Constraint; /** * @Annotation */ class Email extends Constraint { public $message = "The...

Doctrine batch inserting uses 2GB of Ram

php,symfony2,doctrine2,doctrine,batch-insert
I am trying to insert approximately 200k of records with Symfony2 and Doctrine via Doctrine Fixtures Bundle. I am using flush and clear but at the end script uses 1.8 GB of RAM. This is the class that loads SmartMeter entities into database: <?php namespace HTEC\SmartMeteringAPIBundle\DataFixtures\ORM; use Doctrine\Common\DataFixtures\AbstractFixture; use Doctrine\Common\DataFixtures\FixtureInterface;...

doctrine - get next and prev record

mysql,symfony2,doctrine,next
just so i have some record allready fetched. I have date field 'created' and now I want to get next and prev record by date. Got it working by: $qb = $this->createQueryBuilder('a'); $next = $qb->expr()->gt('a.created', ':date'); $prev = $qb->expr()->lt('a.created', ':date'); $prev = $qb->select('partial a.{id,title,created}') ->where($prev) ->setParameter('date', $date) ->orderBy('a.created', 'DESC') ->setMaxResults(1)...

Doctrine column id does not exist on PostgreSQL

sql,database,postgresql,doctrine
I have been forced into using PostgreSQL. I have read something about it but still it's new and I have no idea why I'm getting this error: SQLSTATE[42703]: Undefined column: 7 ERROR: column t0.id does not exist LINE 1: SELECT t0.id AS id1, t0.user AS user2, t0.email AS ma... I...

Implement complex calculations with SQL or rather use ETL?

php,sql,doctrine,business-intelligence,domain-model
We are currently developing a web application for financial analysis using PHP (Zend Framework 2) and Doctrine as ORM-Tool (MySQL database). The complex financial calculations are done on the server-side, since the client has to be simple as possible. The data should be available in nearly "real-time", since the user...

What kind of symfony relationship would be most appropriate?

symfony2,doctrine
I have 2 entities: A Package, and a StockItem. A Package can have many Stockitems, and a StockItem can belong to many Packages, so i assume this is a ManyToMany relationship. But i dont want the StockItems to point towards Packages, cause i assume this will bloat the database. Since...

Configure symfony form label in doctrine config

php,symfony2,doctrine2,doctrine
I am currently on a project where i have a lot of entities with a lot of fields (clients with addresses, phones, age, firm number...), and i am doing it for a French client. So i code in English: class Client { /** * @var integer */ private $id; /**...

Doctrine2 Can't update owning side in a Many-to-one bidirectional relationship

symfony2,doctrine2,doctrine
I have a bidirectional association between entity "Task" and entity "User". "Task" is defined as follows class Task { /** * * @ORM\ManyToOne(targetEntity="User", inversedBy="tasks") */ private user; } And "User" is defined as class User { /** * @ORM\OneToMany(targetEntity="Task", mappedBy="user") */ private $tasks; } Accessing relationship from both directions works...

override translation fallback symfony 2

symfony2,doctrine
I have a symfony 2 project that supports 2 languages in both the backend and the front end. And I have enabled translation fallback in the configuration to allow the admin to view all the database records regardless of what language he chooses to use in the backend. However, for...

Symfony Doctrine findBy and then map

php,symfony2,doctrine2,doctrine
Basically I want to execute this mysql query with doctrine: select distinct user_id from work_hour where project_id = ?; But I don't know how I can do this with pretty Doctrine code. Is it possible to make it look like the following pseudo code or do I have to use...

Fieldset zf2 - populate 2 entities

php,zend-framework2,doctrine
I have a form by adding a fieldset and fieldset that calling another. I have only one ManyToOne relationship referencing the ID of the another entity. in my controler I have: public function juridicaAction() { if (!$this->zfcUserAuthentication()->hasIdentity()) { return $this->redirect()->toRoute('login'); } $objectManager = $this->getServiceLocator()->get('Doctrine\ORM\EntityManager'); $em = $this->getEntityManager(); $pessoajuridica = new...

Unique Entity Error message

api,symfony2,exception-handling,doctrine
I have a user entity which have some unique fields. The code bellow shows you how I defined it. /** * @UniqueEntity(fields={"login"}, message="UNIQUE ERROR MESSAGE") */ ...... /** * @var string * * @ORM\Column(name="login", type="string", length=255, unique=true) */ private $login; Developping an API, I would like to be able to...