Symfony 2 fetch data from many to many relationship with doctrine - symfony

I'm stuck on getting this to work with Symfony2 and Doctrine, the situation:
A page with piercing info (general info and caretaking info).
A care taking can have multiple piercings to which it applies and a piercing can have multiple care takings
Database layout:
Piercings:
id
name
...
Caretaking:
id
title
description
piercing_to_caretaking
id
piercing_id
caretaking_id
Now, how would I create the Entity and the corresponding Query/Dql ?

If you are defining your entities using yml:
In Piercing.orm.yml add:
manyToMany:
caretakings:
targetEntity: Caretaking
inversedBy: piercings
joinTable:
name: piercing_caretaking
joinColumns:
caretaking:
referencedColumnName: id
inverseJoinColumns:
piercing:
referencedColumnName: id
In Caretaking.orm.yml add:
manyToMany:
piercings:
targetEntity: Piercing
mappedBy: caretakings
Generate/update the entities in the usual way, i.e.:
app/console doctrine:schema:update --dump-sql (to check results)
app/console doctrine:schema:update --force (to apply changes)
Then when you have a Piercing or Caretaking entity you can access the related entities like this:
$piercing->addCaretaking($caretaking);
$caretakings = $piercing->getCaretakings();
...
$piercings = $caretaking->getPiercings();
For more information, including how to do this using annotations, see sub-section 5.1.4 Many to Many, Bidirectional in Section 5 Association Mapping of the Doctrine documentation.

Related

Simple Derived Identity issue

I'm struggling with an issue based on the use case that is described here :
Use-Case 2: Simple Derived Identity
I have the following Doctrine entities and mapping in my Symfony app:
class User
{
private $entity_id;
private $address;
...
}
class Address
{
private $user;
...
}
AppBundle\Entity\User:
type: entity
id:
entity_id:
type: integer
generator:
strategy: AUTO
oneToOne:
address:
targetEntity: Address
mappedBy: user
cascade: ["persist"]
AppBundle\Entity\Address:
type: entity
id:
user:
associationKey: true
oneToOne:
user:
targetEntity: User
inversedBy: address
joinColumn:
name: entity_id
referencedColumnName: entity_id
Every time I perform a DQL query that involves the User entity, Doctrine performs one additional query per matching User to retrieve the corresponding Address entity. That happen every time, even if the Address data are never used in the code.
I tried to reproduce this issue on a vanilla Symfony installation, and I faced another issue, I'm not able to perform the following code as I get an error (Entity of type AppBundle\Entity\Address is missing an assigned ID for field 'user'):
$user = (new User())->setAddress(new Address());
$entityManager->persist($user);
$entityManager->flush();
Do you have any hint or what is wrong?
Best regards

Doctrine manyToMany Definition not Working Undefined index: joinTable

I am trying to get a manyToMay bi-directional mapping working on Symfony 3.2.6 / PHP 7.1. I am unable to get the
php bin/console doctrine:schema:update --dump-sql
command to run without an error
[Symfony\Component\Debug\Exception\ContextErrorException]
Notice: Undefined index: joinTable
Definition is as follows:
Busybee\StudentBundle\Entity\Student:
type: entity
table: student
repositoryClass: Busybee\StudentBundle\Repository\StudentRepository
id:
id:
type: integer
id: true
generator:
strategy: AUTO
fields:
startAtSchool:
type: date
manyToMany:
enrolments:
targetEntity: Busybee\StudentBundle\Entity\Enrolment
mappedBy: students
and
Busybee\StudentBundle\Entity\Enrolment:
type: entity
table: enrolment
repositoryClass: Busybee\StudentBundle\Repository\EnrolmentRepository
id:
id:
type: integer
id: true
generator:
strategy: AUTO
fields:
status:
type: string
length: '32'
lastModified:
type: datetime
createdOn:
type: datetime
manyToMany:
students:
targetEntity: Busybee\StudentBundle\Entity\Student
inversedBy: enrolments
If I remove the mappedBy in the Student Entity the SQL will generate using the doctrine:schema:update command. The example at http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/association-mapping.html#owning-and-inverse-side-on-a-manytomany-association shows the joinTable index on the inversedBy entity, and adding the joinTable to this or the mappedBy entity still generates the error Undefined index: joinTable
So, what if anything am I doing wrong? Is this a bug? Any help much appreciated.
Craig
I found the issue here. Not a Doctrine problem, but a subscriber I had written to add a table prefix. I have updated the code for the Table Prefix subscriber to correctly capture when the definition is a manyToMany association and to ignore the non-owning side. I am now using the Table Prefix code from the Doctrine Site at http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/cookbook/sql-table-prefixes.html
Craig.

Doctrine Relationships - referenced Column name as identifier for entity

So I have these 2 Bundles:
UserBundle
BlogBundle
and these 3 Entities:
UserBundle:User
BlogBundle:User
BlogBundle:Article
BlogBundle:User extends UserBundle:User using a bidirectional one to one relationship. The join column name is user_id and it is an association key:
BlogBundle\Entity\User:
type: entity
table: blog_users
id:
user:
associationKey: true
oneToOne:
user:
targetEntity: UserBundle\Entity\User
inversedBy: blog_user
joinColumn:
name: user_id
referencedColumnName: id
Now I want to create a bidirectional one to Many relationship between BlogBundle:User and BlogBundle:Article.
Currently I'm trying this:
BlogBundle:User
oneToMany:
articles:
targetEntity: Article
mappedBy: author
BlogBundle:Article
manyToOne:
author:
targetEntity: User
inversedBy: Article
joinColumn:
name: author
referencedColumnName: user_id
My Problem is, it works, I can access data from UserBundle:User through an Article object, but in the profiler it shows them as not mapped correctly. My guess is it would be possible to do what I'm trying, but I'm just doing something wrong.
What am I missing?
I think the problem is with the inversedBy, where you have to write the name of the field, not the name of the entity.
Here que documentation:
http://doctrine-orm.readthedocs.org/projects/doctrine-orm/en/latest/reference/association-mapping.html#one-to-many-bidirectional
Your code will be:
BlogBundle:User
oneToMany:
articles:
targetEntity: Article
mappedBy: author
BlogBundle:Article
manyToOne:
author:
targetEntity: User
inversedBy: articles
joinColumn:
name: author
referencedColumnName: user_id

Tracking when an entity or its relations have been updated

I am using Symfony 2.4 and doctrine ORM. I have a parent entity, Property, which has many child relations including:
propertyVideos (OneToMany)
propertyPhotos (OneToMany)
propertyLocation (OneToOne)
In the lastUpdated field of the Property entity, I need to store the date and time of the last update of the Property entity or any of its related entities.
Is there an easy way to do this in Symfony/Doctrine?
Easiest bet would be to use the gedmo/doctrine-extensions or (for Symfony) stof/doctrine-extensions-bundle which you can then use the do the following...
Entity\Article:
type: entity
table: articles
fields:
created:
type: date
gedmo:
timestampable:
on: create // $this create
updated:
type: datetime
gedmo:
timestampable:
on: update // $this update
published:
type: datetime
gedmo:
timestmpable:
on: change
field: type.title
value: Published
// $this->type->title changed to "Published"
blah:
type: datetime
gedmo:
timestampable:
on: change
field: type.somethingelse
// $this->type.somethingelse is changed
manyToOne:
type:
targetEntity: Entity\Type
inversedBy: articles

Namespace doesn't contain mapped entities in Symfony 2

I've created a new entity in src/Andrei/StatisticsBundle/Entity/Attribute/Value/ButtonVarchar.php. Here is the code for this class:
<?php
namespace Andrei\StatisticsBundle\Entity\Attribute\Value;
class ButtonVarchar
{
protected $value;
}
and in src/Andrei/StatisticsBundle/Resources/config/doctrine/ButtonVarchar.yml I defined the following mapping information:
Andrei\StatisticsBundle\Entity\Attribute\Value\ButtonVarchar:
type: entity
table: button_attribute_value_varchar
id:
id:
type: integer
generator: { strategy: AUTO }
fields:
value:
type: string
length: 255
manyToOne:
button:
targetEntity: Button
inversedBy: attributeValues
joinColumn:
name: button_id
referencedColumnName: id
For some reason when I run php app/console doctrine:generate:entities I get the following error:
[RuntimeException] Namespace "Andrei\StatisticsBundle\Entity\Attribute\Value" does not contain any mapped entities.
I can't understand why is this happening. Can someone point me to the right direction? Thank you.
Did you add your StatisticsBundle to Doctrine config?
eg:
doctrine:
orm:
auto_mapping: true
mappings:
AndreiStatisticsBundle: ~
You can see mapping problem in the following link:
https://github.com/symfony/symfony/pull/675
It seems that your entities are separated into fine grained packages. In that case you need to specify fully qualified namespace in order for it to work.
targetEntity: Fully\Qualified\Namespace\To\Button
It may also help.
This works:
MyUniqBundle:Entity
This doesn't work:
MyUniqBundle/Entity

Resources