Rectangle 27 0

I was trying to have a many to many relationship with extra fields, and couldn't make it work either... The thing I read in a forum (can't remember where) was:

If you add data to a relationship, then it's not a relationship anymore. It's a new entity.

And it's the right thing to do. Create a new entity with the new fields, and if you need it, create a custom repository to add the methods you need.

would become

and of course, C has ManyToOne relationships with both A and B.

I searched everywhere on how to do this, but in the end, it's the right thing to do, if you add data, it's no longer a relationship.

You can also copy what contains usually do, or try to overwrite it in a custom repository, to do whatever you need it to do.

Is there any reason (other than wanting to only have one -> in your code when following the relation) that you wouldn't want the third entity?

hm... so you say... i have user entity where i would have friends property with OneToMany relationship to Friends Entity where i would have the user_id with ManyToOne Relationship to the UserEntity... (as i have now) + i need to create FriendsData entity where i would have... what? :/ ah so confused...

Please edit the post and tell us what properties would you like to store and where, because maybe it can be solved using only two entities

ManyToMany relationship with extra fields in symfony2 orm doctrine - S...

symfony2 orm many-to-many entity-relationship
Rectangle 27 0

Symfony has nothing to do with this, it's strictly Doctrine's thing. But, no, you do not have to create a AuthorsBooks entity. All you have to do is to configure Doctrine properly, i.e. use @JoinTable annotation that specifies which table should be used to join two entities.

symfony2 - Do Many-To-Many relationships required a "join entity" in S...

symfony2 doctrine2
Rectangle 27 0

In my case a too early call of

$this->entityManager->clear();

caused the problem. It also disappeared by only doing a clear on the recent object, like

$this->entityManager->clear($capture);

symfony2 - Doctrine - A new entity was found through the relationship ...

symfony2 doctrine
Rectangle 27 0

First of all, you should take better care of your code, I see like 3 differents indentations in your entity and controller - this is hard to read, and do not fit the Symfony2 coding standards.

The code you show for your controller is not complete, we have no idea from where $this->activeCapture is coming. Inside you have a $people['capture'] which contains a Capture object I presume. This is very important.

If the Capture in $people['capture'] is persisted / fetched from another EntityManager than $this->entityManager (which, again, we do not know from where it come), Doctrine2 have no idea that the object is already persisted.

You should make sure to use the same instance of the Doctrine Entity Manager for all those operations (use spl_object_hash on the EM object to make sure they are the same instance).

You can also tell the EntityManager what to do with the Capture object.

// Refreshes the persistent state of an entity from the database
$this->entityManager->refresh($captureEntity);

// Or
// Merges the state of a detached entity into the 
// persistence context of this EntityManager and returns the managed copy of the entity.
$captureEntity = $this->entityManager->merge($captureEntity);

If this does not help, you should provide more code.

I tryed to refresh all of the activeCapture entities I have, but nothing... I'm sure that I only have one EntityManager because I use "get('doctrine.orm.default_entity_manager')". The $this->activeCapture is given here : pastebin.com/px0cyWs0 and the getActiveCapture here: pastebin.com/D0LRW2TD

Why are you detaching Captures line 36 of pastebin.com/px0cyWs0 ? If the capture is referenced somewhere, Doctrine doesn't know anything about it anymore and then can throw the kind of exception you got.

This process permit us to refresh the capturing entities, but this function print logs, and is not called (no debug is printed)

symfony2 - Doctrine - A new entity was found through the relationship ...

symfony2 doctrine
Rectangle 27 0

The error: 'Comment#capture' that was not configured to cascade persist operations for entity

dont configured the cascade persist

try with this:

/**
 * @ORM\ManyToOne(targetEntity="Capture", inversedBy="comments", cascade={"persist", "remove" })
 * @ORM\JoinColumn(name="capture_id", referencedColumnName="id",nullable=true)
 */
 protected $capture;

symfony2 - Doctrine - A new entity was found through the relationship ...

symfony2 doctrine
Rectangle 27 0

You need to set the category of the item when you add it otherwise it will be saved in the database as NULL rather than the category id.

/**
 *
 * @param Items $items
 * @return Category
 */
public function addItem(Items $item)
{
    $item->setCategory($this);
    $this->items[] = $item;

    return $this;
}

Qoop, thanks for getting back. But it's not null because of the way data is added. Plus, I tested by adding data to database manually, it is still not working.

symfony2 - Symfony 2 Doctrine 2 one to many relationship not returning...

symfony2 doctrine2
Rectangle 27 0

It does look like a use case for inheritance mapping, unless you have a ton of different entities you want to store addresses for. Using your example in Doctrine, you'd create two classes for each of your addresses.

<?php
namespace MyProject\Model;

/**
 * @Entity
 * @InheritanceType("SINGLE_TABLE")
 * @DiscriminatorColumn(name="type", type="string")
 * @DiscriminatorMap({"event" = "EventAddress", "museum" = "MuseumAddress"})
 */
class Address {
    protected $street;
    // ...
}

/**
 * @Entity
 */
class EventAddress extends Address {
    protected $event;
    // ...
}

/**
 * @Entity
 */
class MuseumAddress extends Address {
    protected $museum;
    // ...
}
@ORM\ManyToOne(targetEntity="Event", inversedBy="addresses")protected $event;

Yep, exactly. In the database an EventAddress will have an empty museum_id field and a MuseumAddress will have an empty event_id field.

Thank you so much! I had a hard time trying to figure inheritance mapping, but now I think I have a clear picture of how it works.

If I could get a bit more clarification, on the one-to-many side of this (the event or museum entities), would the association reference the address entity or the sub-entity? Would it need to specify something like the type when mapping the association?

EventAddress and MuseumAddress are separate entities from the ORM's perspective, so you would want to reference them directly in your relationship. For example, for the address property on our Museum class we'd use this annotation: @ORM\OneToMany(targetEntity="MuseumAddress", inversedBy="museum")

symfony2 - Polymorphic relationship in doctrine 2 - Stack Overflow

symfony2 doctrine2
Rectangle 27 0

The error: 'Comment#capture' that was not configured to cascade persist operations for entity

dont configured the cascade persist

try with this:

/**
 * @ORM\ManyToOne(targetEntity="Capture", inversedBy="comments", cascade={"persist", "remove" })
 * @ORM\JoinColumn(name="capture_id", referencedColumnName="id",nullable=true)
 */
 protected $capture;

symfony2 - Doctrine - A new entity was found through the relationship ...

symfony2 doctrine
Rectangle 27 0

A new entity was found through the relationship 'Application\Entity\User#chats' 
that was not configured to cascade persist operations for entity: ###. 
To solve this issue: Either explicitly call EntityManager#persist() on this unknown entity or
configure cascade persist  this association in the mapping for example @ManyToOne(..,cascade={"persist"}).

My case was that I tried to save entity, that shouldn't be saved. Entity relations was filled and tried to be saved (User has Chat in Many2Many, but Chat was a temporary entity), but there were some collisions.

So If I use cascade={"persist"} I get unwanted behaviour - trash entity is saved. My solution was to remove non-saving entity out of any saving entities:

// User entity code
public function removeFromChats(Chat $c = null){
    if ($c and $this->chats->contains($c)) {
        $this->chats->removeElement($c);
    }
}
/* some code witch $chat entity */
$chat->addUser($user);

// saving
$user->removeFromChats($chat);
$this->getEntityManager()->persist($user);
$this->getEntityManager()->flush();

Hey already mentioned that the entity is there in database , so your answer does not make any sense regarding this question.

@Vivek Well, I found this page via google as the most relative to the error I got, so I had to find solution by myself and finally I left it here to help others with the same error. I am sorry if it is not convinient for you.

symfony2 - Doctrine - A new entity was found through the relationship ...

symfony2 doctrine
Rectangle 27 0

This really looks like a bidirectional many to many with customer and article. The entities you would build are Customer.php and Article.php, and you would specify a many-to-many in those files via annotation, or in doctrine.orm.yml depending on your preference.

You would use DQL:

$query = $em->createQuery("SELECT a FROM Article a JOIN a.customer c");
$users = $query->getResult();

Then you would process articles as entities, and call article.getCustomer() for a list of customers associated with an article.

Thanks for your feedback. I'm a bit confused does this mean i have to delete my CustomerArticle Entity and with it the created table? You wrote "Doctrine will make the intermediate table for you (customer_article) and manage it." Does this mean the fact that i make a many-to-many annotation in Customer.php and Article.php ensures that Doctrine will create a table "customer_article" without having it specified in CustomerArticle.php? As far as i understand your DQL-Example i can also do it vice versa to get all articles associated with an user? It's realy a different approach - thank you

If, AND ONLY IF, you have other properties associated with the many-to-many join you will need to manually specify the join table. Otherwise, you do not need it as an entity. If there are no other fields besides the foreign keys, you should delete it and let doctrine handle that for you. And you are right about the inverse query $query = $em->createQuery("SELECT c FROM Customer c JOIN c.article a"); being necessary to get a list of customers .

mysql - Symfony2 / Doctrine Relationship Mapping - Stack Overflow

mysql symfony2 doctrine entity-relationship
Rectangle 27 0

<?php
// xxxxBundle/Entity/Guest.php

namespace xxxxBundle\Entity;

use Symfony\Component\Validator\Mapping\ClassMetadata;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Constraints\Email;
use Symfony\Component\Validator\Constraints\MinLength;
use Symfony\Component\Validator\Constraints\MaxLength;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="guest")
 */
class Guest
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
    * @ManyToMany(targetEntity="Category", inversedBy="guests")
    * @JoinTable(name="guests_categories")
    */
    protected $categories;

    /**
    * @ManyToMany(targetEntity="Event", inversedBy="events")
    * @JoinTable(name="guests_events")
    */
    protected $events;

    /**
     * @ORM\Column(type="string", length=30)
     */
    protected $name;

    /**
     * @ORM\Column(type="string", length=30)
     */
    protected $surname;

    /**
     * @ORM\Column(type="string", length=30)
     */
    protected $email;

    /**
     * @ORM\Column(type="string", length=100)
     */
    protected $address;

    /**
     * @ORM\Column(type="string", length=10)
     */
    protected $phone;

    /**
     * @ORM\Column(type="string", length=10)
     */
    protected $mobile;

    /**
     * @ORM\Column(type="text")
     */
    protected $description;

    /**
     * @ORM\Column(type="datetime")
     */
    protected $created_at;

    /**
     * @ORM\Column(type="datetime")
     */
    protected $updated_at;

    /**
     * @ORM\Column(type="string")
     */
    protected $token;

    /**
     * @ORM\Column(type="boolean")
     */
    protected $is_activated;

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

    public static function loadValidatorMetadata(ClassMetadata $metadata)
    {
        $metadata->addPropertyConstraint('name', new NotBlank());
        $metadata->addPropertyConstraint('surname', new NotBlank());
        $metadata->addPropertyConstraint('email', new Email(array(
            'message' => 'I do not like invalid emails. Give me a real one!')));

        $metadata->addPropertyConstraint('phone', new MaxLength(10));
        $metadata->addPropertyConstraint('mobile', new MaxLength(10));

    }    

}
<?php
// xxxxBundle/Entity/Category.php

namespace xxxxBundle\Entity;

use Symfony\Component\Validator\Mapping\ClassMetadata;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Constraints\Email;
use Symfony\Component\Validator\Constraints\MinLength;
use Symfony\Component\Validator\Constraints\MaxLength;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="category")
 */
class Category
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
    * @ManyToMany(targetEntity="Guest", mappedBy="categories")
    */
    protected $guests;

    /**
     * @ORM\Column(type="string", length=30)
     */
    protected $name;

    /**
     * @ORM\Column(type="text")
     */
    protected $description;

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

    public static function loadValidatorMetadata(ClassMetadata $metadata)
    {
        $metadata->addPropertyConstraint('name', new NotBlank());

    }    

}
<?php
// xxxxBundle/Entity/Event.php

namespace xxxxBundle\Entity;

use Symfony\Component\Validator\Mapping\ClassMetadata;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Constraints\Email;
use Symfony\Component\Validator\Constraints\MinLength;
use Symfony\Component\Validator\Constraints\MaxLength;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="event")
 */
class Event
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
    * @ManyToMany(targetEntity="Guest", mappedBy="categories")
    */
    protected $guests;

    /**
     * @ORM\Column(type="string", length=30)
     */
    protected $name;

    /**
     * @ORM\Column(type="string", length=100)
     */
    protected $location;

    /**
     * @ORM\Column(type="text")
     */
    protected $description;

    /**
     * @ORM\Column(type="datetime")
     */
    protected $scheduled_at;

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

    public static function loadValidatorMetadata(ClassMetadata $metadata)
    {
        $metadata->addPropertyConstraint('name', new NotBlank());
        $metadata->addPropertyConstraint('location', new NotBlank());
    }    

}

I feel confused about the Attendance entity. The Attendance entity will have the following variables:

I do not know which will be the primary key (or the primary keys?). The db table does not need to have a separate Id (or not?).

<?php
// xxxxBundle/Entity/Attendance.php

namespace xxxxBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="attendance")
 */
class Attendance
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
    * @ManyToMany(targetEntity="Guest", mappedBy="categories")
    */
    protected $guests;

    /**
    * @ManyToMany(targetEntity="Event", mappedBy="events")
    */
    protected $events;

    /**
     * @ORM\Column(type="string", length=3)
     */
    protected $will_attend;

    /**
     * @ORM\Column(type="text")
     */
    protected $description;

    /**
     * @ORM\Column(type="datetime")
     */
    protected $replied_at;

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

}

I executed the create entities command, the schema update --force and crud for every entity. Everything seem to work fine ! Except when I am trying to edit an entry of the Attendance entity that I am getting the following error : Notice: Undefined index: guests in /.../vendor/doctrine/lib/Doctrine/ORM/Persisters/BasicEntityPersister.php line 808 500 Internal Server Error - ErrorException I suppose there is a problem with the manytomany relations of the events/guests entities.

How do I connect multiple relationships in symfony2 with doctrine? - S...

symfony2 doctrine
Rectangle 27 0

oneToMany:
    oneToMany:
        texts:
            targetEntity: Acme\TextBundle\Entity\Text
            mappedBy: reservation
        emails:
            targetEntity: Acme\EmailBundle\Entity\Email
            mappedBy: reservation

symfony2 - Two OnetoMany relationships on an entity causes error? - St...

symfony2 doctrine relationships
Rectangle 27 0

Had similar problem and this trick solved it, Thanks!!!!!

orm - Symfony2 and Doctrine, Column cannot be null with OneToOne relat...

symfony2 orm doctrine one-to-one
Rectangle 27 0

It is possible to create a function like the following ...

public function findRandomProduct()
{
   return $this->createQueryBuilder('p')
      ->orderBy('RAND()')
      ->getQuery()
      ->getSingleResult();
}

php - Symfony2 Doctrine get random product from a category - Stack Ove...

php symfony2 doctrine entity relationships
Rectangle 27 0

The query is wrong. When you do a left join it selects rows from the left table. Just flip them.

$qb = $this->_em->createQueryBuilder()
        ->select('c, p')
        ->from('c.posts', 'p')
        ->leftJoin('...Blog\Category', 'c')
        ->where($qb->expr()->andX(
           $qb->expr()->eq('c.id', ':id'),
           $qb->expr()->eq('p.category_id', 'c.id')
         )
        ->orderBy('p.created', 'DESC')
        ->setParameter(':id', $catId);

But isn't that very slow to first join all entries and then select the ones which should be returned?

I don't think it does it the way you say.

symfony2 - Doctrine many-to-many relationship seletct - Stack Overflow

symfony2 doctrine2 doctrine
Rectangle 27 0

I'd suggest to make another query where you select Posts of a specific category.

symfony2 - Doctrine many-to-many relationship seletct - Stack Overflow

symfony2 doctrine2 doctrine
Rectangle 27 0

// Example - $qb->expr()->in('u.id', array(1, 2, 3))
// Make sure that you do NOT use something similar to $qb->expr()->in('value', array('stringvalue')) as this will cause Doctrine to throw an Exception.
// Instead, use $qb->expr()->in('value', array('?1')) and bind your parameter to ?1 (see section above)
public function in($x, $y); // Returns Expr\Func instance

EDIT There is an SQL statement which allow you to filter rows that only check all of given values. It's ALL statement.

// Example - $qb->expr()->all($qb2->getDql())
public function all($subquery); // Returns Expr\Func instance
$subquery
SELECT id_categorie FROM budget_categorie WHERE id_budget = '$idBudget'

Yes, but the problem with in function is, that the $x parameter can be only a single value (meaning that in will return all results that have the same id as those in array in $y parameter) and I can't do in('bud.tags', array(1,2,3))

Problem is in 'bud.tags' not in the array, bud.tags is an array and it has to be single value

Sorry for my confusion. I'm searching for the good issue now... ;) Could you show the part of the database which store budget and budget_categories?

Thank you I'll take a look at the all statement and let you know where I got :), if I still won't be to solve it I'll update my question with db and entity classes

doctrine - Symfony2 Querybuilder - Many to many relationship - Stack O...

symfony2 doctrine many-to-many query-builder
Rectangle 27 0

add and remove are used to deal with collections. If for example your Entity (Let's say A) contains a collection of B elements, then the command will provide an addB() and a removeB() public methods to help you add and remove elements from your collection. It'll also provide a getter which returns the whole collection.

The command generates methods based on the type of attributes you're working with (ArrayCollection, string, ...)

doctrine - Symfony2 getters, setters, add and remove - Stack Overflow

symfony2 doctrine entity relationships
Rectangle 27 0

If you have the $blogPost, just persist it, the same as the comments. Also flush at the end:

$form = $this->createForm(new CommentsType(), array('comments' => $comments));

if ($request->getMethod() == "POST")
{
    $form->bind($request);

    foreach($comments as $comment) {
        $doctrine->persist($comment);
    }
    $doctrine->persist($blogPost);
    $doctrine->flush();
}

return $this->render('blah.html.twig', array('blog' => $blogPost, 'comments' => $comments, 'form' => $form->createView());

That's a solution but wouldn't it be better (or maybe easier) to persist only $blogPost and use cascade=all on the relationship?

cheesemacfly's suggestion might work if you have access to the orm.yml or entity/annotation code. My experience with cascade has not been uniformly good, largely due to somewhat more complex models that presented herein.

php - Symfony2, Doctrine, and forms - Persisting the data of both side...

php symfony2 doctrine
Rectangle 27 0

Item
Category
<?php

namespace YourApplication\Bundle\DatabaseBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="Categories")
 */
class Category
{
    /**
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\ManyToMany(targetEntity="Item", inversedBy="categories")
     * @ORM\JoinTable(name="ItemsToCategories")
     */
    protected $items;

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

<?php

namespace YourApplication\Bundle\DatabaseBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="Items")
 */
class Item
{
    /**
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\ManyToMany(targetEntity="Category", mappedBy="items")
     */
    protected $items;

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

Since a category owns the items and the items are owned by the categories, Category will be the owning side and Item will be the inverse side of the relationship.

symfony2 - What is the recommended doctrine relationship between these...

symfony2 doctrine2