通过理论实体插入外键


inserting foreign key via doctrine entity?

我正在使用Doctrine2 + CodeIgniter2,并尝试创建连接表的简单测试。

以下是我对所涉及的两个表的架构:

创建表test_lastnames(ID INT AUTO_INCREMENT不为空,last_name VARCHAR(255) 不为 NULL,主键(id)) 引擎 = InnoDB;

创建表test_firstnames(ID INT AUTO_INCREMENT不为空, mylastname_id INT 默认值为空,first_name VARCHAR(255) 不为空, 索引 IDX_23D7305696EC0FA4 (mylastname_id),主键 (ID)) 引擎 = 创新数据库;

更改表test_firstnames添加约束FK_23D7305696EC0FA4外部约束 键 (mylastname_id) 引用test_lastnames (ID)

这是我的 YAML 映射

ORM'Testing'Firstnames:
  type: entity
  table: test_firstnames
  fields:
    id:
      type: integer
      id: true
      generator:
        strategy: AUTO
    firstname:
      type: string
      column: first_name
  manyToOne:
    mylastname:
      targetEntity: ORM'Testing'Lastnames

ORM'Testing'Lastnames:
  type: entity
  table: test_lastnames
  fields:
    id:
      type: integer
      id: true
      generator:
        strategy: AUTO
    lastname:
      type: string
      column: last_name

我正在尝试将数据写入表。

$new_lastname = new ORM'Testing'Lastnames;
$new_lastname -> setLastName ('Shakespear');
$this->doctrine->em->persist($new_lastname);
$this->doctrine->em->flush();
$new_firstname = new ORM'Testing'Firstnames;
$new_firstname->setFirstname('William');
$new_firstname->setMyLastName($new_lastname ->getID());
$this->doctrine->em->persist($new_firstname);
$this->doctrine->em->flush();

它返回以下错误:

消息:传递给 ORM''Testing''Firstnames::setMylastname() 的参数 1 必须是 ORM''Testing''Lastnames 的实例,给定整数,在第 31 行的/[PATH]/applicationFolder/controllers/testing/test_namejoins_insert.php 中调用并定义

文件名:测试/名字.php

行号:66

以及一堆Message: spl_object_hash() expects parameter 1 to be object, integer given错误。

这是 Firstnames.php 中的第 66 行: public function setMylastname('ORM'Testing'Lastnames $mylastname = null)

我还没有开始破解它 - 问题就在那里吗 $mylastname = null"?

如何按实体插入外键值?

$new_firstname->setMyLastName($new_lastname);

而不是$new_firstname->setMyLastName($new_lastname ->getID());