Doctrine2 двунаправленный ManyToMany — неопределенный индекс

#php #doctrine-orm

#php #doctrine-orm

Вопрос:

Добавление нового любимого блюда для пользователя (это работает):

 $user = $em->getRepository('user')->find($userId);
$dish = $em->getRepository('dish')->find($dishId);
$user->addFavouriteDish($dish);
$em->persist($user);
$em->flush();
  

Получение всех пользователей, у которых блюдо является любимым (это не работает)

 $dish = $em->getRepository('dish')->find($dishId);
echo 'There are '.count($dish->getFavouriteUsers()).' users that has this dish as a favourite';
  

Ошибка из приведенного выше:

 string(23) "Undefined index: dish"
string(88) "/srv/www/project/vendor/doctrine/orm/lib/Doctrine/ORM/Persisters/BasicEntityPersister.php"
  

Присоединиться к таблице:

 dinner.user_dish
id, user_id, dish_id
  

объекты, созданные доктриной:

 /entities/user.php

use DoctrineORMMapping as ORM;

/**
 * user
 *
 * @ORMTable(name="user")
 * @ORMEntity
 * @ORMHasLifecycleCallbacks
 */
class user
{

  ...

  /**
   * @var DoctrineCommonCollectionsCollection
   *
   * @ORMManyToMany(targetEntity="dish", inversedBy="user")
   * @ORMJoinTable(name="user_dish",
   *   joinColumns={
   *     @ORMJoinColumn(name="user_id", referencedColumnName="id", onDelete="CASCADE")
   *   },
   *   inverseJoinColumns={
   *     @ORMJoinColumn(name="dish_id", referencedColumnName="id", onDelete="CASCADE")
   *   }
   * )
   */
  private $favouriteDishes;

  /**
   * Constructor
   */
  public function __construct()
  {
      $this->session = new DoctrineCommonCollectionsArrayCollection();
      $this->favouriteDishes = new DoctrineCommonCollectionsArrayCollection();
  }

  ...

  /**
   * Add favouriteDishes
   *
   * @param dish $favouriteDishes
   * @return user
   */
  public function addFavouriteDish(dish $favouriteDishes)
  {
      $this->favouriteDishes[] = $favouriteDishes;

      return $this;
  }


/entities/dish.php

use DoctrineORMMapping as ORM;

/**
 * dish
 *
 * @ORMTable(name="dish")
 * @ORMEntity
 */
class dish
{

  ...

  /**
   * @var DoctrineCommonCollectionsCollection
   *
   * @ORMManyToMany(targetEntity="user", mappedBy="dish")
   */
  private $favouriteUsers;

  /**
   * Constructor
   */
  public function __construct()
  {
      $this->favouriteUsers = new DoctrineCommonCollectionsArrayCollection();
  }

  ...

  /**
   * Get favouriteUsers
   *
   * @return DoctrineCommonCollectionsCollection 
   */
  public function getFavouriteUsers()
  {
      return $this->favouriteUsers;
  }
  

файлы yaml:

 /config/yaml/user.dcm.yml

user:
  type: entity
  id:
    id:
      type: integer
      generator:
        strategy: AUTO
  fields:
    displayname:
      type: string
      length: 60
      unique: true
    email:
      type: string
      length: 255
      unique: true
    hash:
      type: string
      length: 60
  manyToMany:
    favouriteDishes:
      targetEntity: dish
      inversedBy: user
      joinTable:
        name: user_dish
        joinColumns:
          user_id:
            referencedColumnName: id
        inverseJoinColumns:
          dish_id:
            referencedColumnName: id
  oneToMany:
    session:
      targetEntity: session
      mappedBy: user
  lifecycleCallbacks:
    prePersist: [ hashPassword ]


/config/yaml/dish.dcm.yml

dish:
  type: entity
  id:
    id:
      type: integer
      generator:
        strategy: AUTO
  fields:
    title:
      type: string
      length: 255
    description:
      type: text
    image:
      type: string
      length: 255
  manyToMany:
    favouriteUsers:
      targetEntity: user
      mappedBy: dish
  

Ответ №1:

ManyToMany в вашем объекте dish говорит, что это так mappedBy: dish . Однако на самом деле он отображается с помощью favouriteDishes . Просто измените это на favouriteDishes :

 dish:
  type: entity
  id:
    id:
      type: integer
      generator:
        strategy: AUTO
  fields:
    title:
      type: string
      length: 255
    description:
      type: text
    image:
      type: string
      length: 255
  manyToMany:
    favouriteUsers:
      targetEntity: user
      mappedBy: favouriteDishes
  

Комментарии:

1. Я серьезно люблю тебя прямо сейчас. Невероятно, насколько слепым вы можете стать, слишком долго глядя на одну и ту же проблему! Спасибо! Скоро будет принят в качестве ответа (тайм-аут)