Doctrine2使我对OneTomany和许多人的关系使我发疯



我尝试使用Doctrine2映射,但是在遇到了8个小时的问题后,我真的需要您的帮助。

我有3个PostgreSQL表,第一个是房子

 Column  |      Type      |                     Modifiers                      
---------+----------------+----------------------------------------------------
 id      | integer        | not null default nextval('house_id_seq'::regclass)
 name    | character(255) | not null
 address | character(255) | 
 rooms   | integer        | not null
Indexes:
    "house_pkey" PRIMARY KEY, btree (id)
Referenced by:
    TABLE "room" CONSTRAINT "room_house_id_fkey" FOREIGN KEY (house_id) REFERENCES house(id) ON UPDATE CASCADE ON DELETE CASCADE

第二个是

Table "public.room"
  Column   |          Type          |                     Modifiers                     
-----------+------------------------+---------------------------------------------------
 id        | integer                | not null default nextval('room_id_seq'::regclass)
 name      | character varying(255) | 
 room_type | integer                | 
 vacant    | boolean                | 
 house_id  | integer                | 
Indexes:
    "room_pkey" PRIMARY KEY, btree (id)
Foreign-key constraints:
    "room_house_id_fkey" FOREIGN KEY (house_id) REFERENCES house(id) ON UPDATE CASCADE ON DELETE CASCADE

最后一个是

 Table "public.category"
   Column   |      Type      |                       Modifiers                       
------------+----------------+-------------------------------------------------------
 id         | integer        | not null default nextval('category_id_seq'::regclass)
 name       | character(255) | not null
 min_person | integer        | not null
 max_person | integer        | not null
Indexes:
    "category_pkey" PRIMARY KEY, btree (id)

我在室内插入一个fk

在我的Zend Framework2中,我的实体将其声明为

namespace StructuresEntity;
use DoctrineORMMapping as ORM;
/**
 * StructuresEntityHouse
 *
 * @ORMTable(name="house")
 * @ORMEntity(repositoryClass="StructuresEntityRepositoryHouseRepository")
 */
class House
{
    /**
     * @var integer $id
     *
     * @ORMColumn(name="id", type="integer", nullable=false)
     * @ORMId
     * @ORMGeneratedValue(strategy="SEQUENCE")
     * @ORMSequenceGenerator(sequenceName="house_id_seq", allocationSize=1, initialValue=1)
     */
    private $id;
    /**
     * @var string $name
     *
     * @ORMColumn(name="name", type="string", length=255, nullable=false)
     */
    private $name;
    /**
     * @var string $address
     *
     * @ORMColumn(name="address", type="string", length=255)
     */
    private $address;
    /**
     * @var string $rooms
     *
     * @ORMColumn(name="rooms", type="integer", nullable=false)
     */
    private $rooms;
    /**
     *
     * @ORMOneToMany(targetEntity="StructuresEntityRoom", mappedBy="house", cascade={"remove", "persist"})
     */
    protected $house_room;
}

/**
 * StructuresEntityRoom
 *
 * @ORMTable(name="room")
 * @ORMEntity(repositoryClass="StructuresEntityRepositoryRoomRepository")
 */
class Room {
    /**
     * @var integer $id
     *
     * @ORMColumn(name="id", type="integer", nullable=false)
     * @ORMGeneratedValue(strategy="AUTO")
     * @ORMId
     */
    private $id;
    /**
     * @var string $name
     *
     * @ORMColumn(name="name", type="string", length=255,nullable=false)
     */
    private $name;

    /**
     * @var boolean $vacant
     *
     * @ORMColumn(name="vacant", type="boolean", nullable=false)
     */
    private $vacant;

    /**
     * @var StructuresEntityCategory
     *
     * @ORMManyToOne(targetEntity="StructuresEntityCategory" , cascade={"persist", "remove"})
     * @ORMJoinColumns({
     *  @ORMJoinColumn(name="room_type", referencedColumnName="id")
     * })
     */
    private $category;

    /**
     * @ORMManyToOne(targetEntity="StructuresEntityHouse", inversedBy="house_room", cascade={"remove", "persist"})
     *
     */
    private $house;
}
/**
 * StructuresEntityCategory
 *
 * @ORMTable(name="category")
 * @ORMEntity(repositoryClass="StructuresEntityRepositoryCategoryRepository")
 *
 */
class Category {
    /**
     * @var integer $id
     *
     *
     * @ORMColumn(name="id", type="integer", nullable=false)
     * @ORMGeneratedValue(strategy="AUTO")
     * @ORMId
     *
     */
    private $id;
    /**
     * @var string $name
     *
     * @ORMColumn(name="name", type="string", length=255, nullable=false)
     *
     */
    private $name;
    /**
     * @var integer $min_person
     * @ORMColumn(name="min_person", type="integer" , nullable=false)
     */
    private $min_person;
    /**
     * @var integer $max_person
     * @ORMColumn(name="max_person", type="integer", nullable=false)
     */
    private $max_person;
}

与房间和类别的关系也有效。

一个人关注的房间和房屋桌根本不起作用。我无法成功地将FK house_id与房屋表上的ID列映射。所有编辑/保存操作失败,house_id一直设置为NULL

请让我了解我在哪里犯错,我发疯

更新:

我试图改变房屋与房间之间的关系。我删除了房子一侧的onetomany,并在

中更改了许多人
/**
 * @var StructureEntityStructure
 *
 * @ORMManyToOne(targetEntity="StructuresEntityHouse")
 * @ORMJoinColumns({
 *  @ORMJoinColumn(name="house_id", referencedColumnName="id", nullable=FALSE)
 * })
 */
private $house;

当我带有

的房间时
$room = $this->roomService->getRoom($id);
var_dump($room);

我有

object(StructuresEntityRoom)#383 (4) 
{ 
    ["id":"StructuresEntityRoom":private]=> int(77)             
    ["name":"StructuresEntityRoom":private]=> string(33) "my room" 
    ["structure":"StructuresEntityRoom":private]=> object(StructuresEntityHouse)#339 (4) { 
    ["id":"StructuresEntityHouse":private]=> int(3) 
    ["name":"StructuresEntityHouse":private]=> string(255) "hotel2b " 
    ["address":"StructuresEntityHouse":private]=> string(255) "hotel2b avenue" 
    ["number_of_rooms":"StructuresEntityHouse":private]=> int(20) } 
    ["house_id":"StructuresEntityRoom":private]=> int(3) 
}

如果我使用oneTomany关系var_dump($ room)返回我的完整页面,我不知道这意味着什么!

仍然,当编辑房间时,列House_is一直设置为null。仍在工作

更新:09 3月

花了几个小时来阅读教程后,我从一开始就写了所有内容。房屋实体不再退出。结构实体是新的实体。我的问题:使用Doctrine2使用OneTomany和Moantoone关系添加和编辑数据。

我的解决方案:

我的实体是命名空间结构 Entity;

使用Doctrine orm 映射为ORM;

/**
 * StructuresEntityStructure
 *
 * @ORMTable(name="room")
 * @ORMEntity(repositoryClass="StructuresEntityRepositoryRoomRepository")
 */
class Room {
/**
 * @var integer $id
 *
 * @ORMColumn(name="id", type="integer", nullable=false)
 * @ORMGeneratedValue(strategy="AUTO")
 * @ORMId
 */
private $id;
/**
 * @var string $name
 *
 * @ORMColumn(name="name", type="string", length=255,nullable=false)
 *
 */
private $name;
/**
 * @var integer structure_id
 * @ORMColumn(name="structure_id", type="integer", nullable=false)
 */
private $structure_id;
/**
 * @var StructureEntityStructure
 *
 * @ORMManyToOne(targetEntity="Structure", inversedBy="rooms")
 * @ORMJoinColumns({
 *  @ORMJoinColumn(name="structure_id", referencedColumnName="id")
 * })
 */
private $structure;


public function __construct()
{
  //  $this->structure = new DoctrineCommonCollectionsArrayCollection();
}
/**
 * @param $data
 */
public function exchangeArray($data)
{
    $this->fillWith($data);
}

/**
 * @param $data
 * @return Room
 */
public static function createFromArray($data)
{
    $room = new Room();
    $room->fillWith($data);
    return $room;
}
public function updateFromArray($room)
{
    $structure_id = $room->getStructureId();
    $structure = $this->getStructure($structure_id);
    $room->setStructure($structure);
    return $room;

}


/**
 * Sets id
 * @param $i_id
 */
private function set_Id($i_id) {
    $this->id = $i_id;
}
/**
 * Gets id
 * @return integer
 *
 */
public function getId() {
    return $this->id;
}
/**
 * Set name
 * @param string name
 *
 */
public function setName($name) {
    $this->name = $name;
}
/**
 * Get name
 * @return string
 *
 */
public function getName() {
    return $this->name;
}
public function getStructureId()
{
    return $this->structure_id;
}
/**
 *
 * @return DoctrineCommonCollectionsArrayCollection|StructureEntityStructure
 */
public function getStructure() {
    return $this->structure;
}
public function setStructure($structure) {
    $this->structure = $structure;
}

和结构

namespace StructuresEntity;
use DoctrineORMMapping as ORM;
/**
 * StructuresEntityStructure
 *
 * @ORMTable(name="structure")
 * @ORMEntity(repositoryClass="StructuresEntityRepositoryStructureRepository")
 */
class Structure {

/**
 * @var integer $id
 *
 * @ORMColumn(name="id", type="integer", nullable=false)
 * @ORMId
 * @ORMGeneratedValue(strategy="SEQUENCE")
 * @ORMSequenceGenerator(sequenceName="structure_id_seq", allocationSize=1, initialValue=1)
 *
 */
private $id;
/**
 *  @var string address
 *
 * @ORMColumn(name="name", type="string", length=255,nullable=false)
 */
private $name;
/**
 * @var string address
 *
 * @ORMColumn(name="address", type="string", length=255,nullable=false)
 *
 */
private $address;

/**
 * @var integer $rooms
 *
 * @ORMColumn(name="number_of_rooms", type="integer",  nullable=false)
 */
private $number_of_rooms;

/**
 * @ORMOneToMany(targetEntity="Room", mappedBy="structure")
 */
private $rooms;

public function __construct() {
    $this->rooms = new DoctrineCommonCollectionsArrayCollection();
}



public function exchangeArray($data) {
    $this->fillWith($data);
}
public static function createFromArray($data)
{
    $structure = new Structure();
    $structure->fillWith($data);
    return $structure;
}
private function set_Id($i_id) {
    $this->id = $i_id;
}
/**
 * Get id
 * @return integer
 *
 */
public function getId() {
    return $this->id;
}
/**
 * Set name
 * @param string name
 *
 */
public function setName($name) {
    $this->name = $name;
}
/**
 * Get name
 * @return string
 *
 */
public function getName() {
    return $this->name;
}
/**
 * Set address
 * @param string address
 *
 */
public function setAddress($address) {
    $this->address = $address;
}
/**
 * Get address
 * @return string
 *
 */
public function getAddress() {
    return $this->address;
}
/**
 * Set rooms
 * @params integer rooms
 *
 */
public function setRoom($room) {
    $this->rooms = $room;
}
/**
 * Get rooms
 * @return integer
 *
 */
public function getRoom() {
    return $this->rooms;
}
/**
 * @param $rooms
 */
public function setNumberOfRooms($number_of_rooms) {
    $this->number_of_rooms = $number_of_rooms;
}
/**
 * @return int
 */
public function getNumberOfRooms() {
    return $this->number_of_rooms;
}

创建一个新房间时,我调用一个函数来处理我的zend form form data

public function processForm() {
  if ($this->request->isPost()) {
        // get the post data
        $post = $this->request->getPost()->toArray();
        // fill form
        $this->form->setData($post);
        // check if form is valid
        if (!$this->form->isValid()) {
            //prepare view
            $view = new ViewModel(array('form' => $this->form,
                                        'title' => 'Process Form : 
              Some errors during rooms processing'));
            $view->setTemplate('structures/rooms/create');
                return $view;
        }
        /* here I set the structure's Id from $structure obj gets from 
          $this->params('id') 
        */
        $structure = $this->getStructureFromQuerystring();
        $post['structure_id'] = $structure->getId();
        /* here I call a service method to create a Room instance and fills it 
           with data from $this->form
        */
        $return = $this->roomService->insertRoomFromArray($post);
        if ($return ) {
            $this->flashMessenger()->setNamespace('rooms')->addMessage
            ('Operation executed correctly');
            return $this->redirect()->toRoute('rooms/index');
        } 
     }

服务方法

public function insertRoomFromArray(array $am_formData) {
    /* here I get the structure with the id stores in $am_formData*/
    $structure = $this->getStructure($am_formData['structure_id']);
    /* here I copy the $structure obj in $am_formData array */
    $am_formData['structure'] = $structure;
    /* here I call the Room Entity method createFromArray to create the Room */
    $I_event = Room::createFromArray($am_formData);
    /* here I call the mapper method to persist data */
    $this->I_mapper->saveRoom($I_event);
    return $I_event;
}

房间实体

public static function createFromArray($data)
{
    /* create new Room obj */
    $room = new Room();
    /* fill with data */
    $room->fillWith($data);
    return $room;
}
public function fillWith($data) {
    $this->id = (isset($data['id'])) ? $data['id'] : null;
    $this->name = (isset($data['name'])) ? $data['name'] : null;
    /* here I copy the structure obj for relationship */
    $this->structure = (isset($data['structure'])) ? $data['structure'] : null;
} 

映射器实体 公共功能储物室( structures Entity Room $ Room) {

    $this->entityManager->persist($room);
    $this->entityManager->flush();
}

它有效,新房间具有正确的结构ID集。

当我必须编辑房间时,什么?我的解决方案

来自控制器

public function editAction() {
   /* Gets the room obj by $this->params('id') */
   $room = $this->getRoomFromQueryString();

    $this->form->bind($room);
    $view = $this->processEditForm($room);
    if (!$view instanceof ViewModel) {
        $view = new ViewModel(array('form' => $this->form,
            'title' => 'Edit Room: ' . $room->getName() , 
            'structure' => $room->getStructure()));
        $view->setTemplate('structures/rooms/create');
    }
    return $view;
}
private function processEditForm(Room $room)
{
    if ($this->request->isPost()) {
        $post = $this->request->getPost()->toArray();
       /* here I put structure_id in $post array. */
        $post['structure_id'] = $room->getStructure()->getId();
        /* After this , my previous room obj is update with the data come from the
           From, but the $structure entity is NULL. I don't know why. I will use the id
           stores in $post['structure_id'] to fetch the Structure obj*/ 
        $this->form->setData($post);

        if (!$this->form->isValid()) {
            $view = new ViewModel(array('form' => $this->form,
            'title' => 'Some erros during rooms processing'));
            $view->setTemplate('structures/rooms/create');
            return $view;
        }
         $return = $this->roomService->updateRoomFromArray($room);
        if ($return ) {
            $this->flashMessenger()->setNamespace('rooms')->addMessage('Operation executed correctly');
            return $this->redirect()->toRoute('rooms/index');
        }
        else {
            echo "Errore durante Editing della room";
        }
    }

}

更新数据的服务方法 公共功能updaterroomraray(房间$ room){ /*我致电房间实体方法以更新我的房间/ $ i_event = Room :: UpdateFromArray($ ROOM); /持久数据 */ $ this-> i_mapper-> updateroom($ room); }

public function updateFromArray($room)
{
    /* here I fetch the Structure's relationship my Room obj belongs to */
    $structure_id = $room->getStructureId();
    $structure = $this->getStructure($structure_id);
    /* here I set the link*/
    $room->setStructure($structure);
    return $room;

}
public function updateRoom(StructuresEntityRoom $room)
{
    $this->entityManager->merge($room);
    $this->entityManager->flush();
}

请我知道您对我的代码的看法。使用Doctrine2的正确方法是正确的吗?预先感谢

注释的语法不正确。

您的许多人协会必须具有以下简单格式:

@manytoone(targetentity =; structures Entity house&quort&quort&quoted =;@joincolumn(name =" house_id;

查看文档以获取更多信息:http://doctrine-orm.readthedocs.org/en/latest/Reference/Association-mapping.html#one-to-to-many-bidirectional

希望这会有所帮助。

相关内容

  • 没有找到相关文章