php - Doctrine 2 : how to auto-get data of related tables?

标签 php mysql doctrine-orm doctrine

我得到了这样的模型:

class Address{
   /** @id @Column(type="integer") @GeneratedValue**/
   public $id;
   /**  @name @Column(type="string")**/
   public $name;
}
class User{
   /** @id @Column(type="integer") @GeneratedValue**/
   public $id;
   /**
   * @OneToOne(targetEntity="Address")
   * @JoinColumn(name="id_address", referencedColumnName="id")
   */
   public $address
}

以及 MySql 上的架构:

CREATE TABLE User (
id INT AUTO_INCREMENT NOT NULL,
address_id INT DEFAULT NULL,
PRIMARY KEY(id)
) ENGINE = InnoDB;

CREATE TABLE Address (
id INT AUTO_INCREMENT NOT NULL,
PRIMARY KEY(id)
) ENGINE = InnoDB;

ALTER TABLE User ADD FOREIGN KEY (address_id) REFERENCES Address(id);

当我尝试使用以下代码从 mySql 获取数据时:

    $this->model = new stdclass;
    $this->model->address = new AddressModel(); 
    $this->model->user = new UserModel();
    $adr=$this->model->address->getItem(1);
    $user=$this->model->user->getItem(1);
    var_dump($user);exit();

在结果中,我得到了用户的所有值(包括其地址的值)。 当我评论 $adr=$this->model->address->getAll();

我会得到错误:

 Warning: require(C:\WINDOWS\TEMP\__CG__Address.php)

我意识到 Doctrine 仅在我加载所需的所有数据时进行映射。

这是我的问题: 如何使 Doctrine 仅通过查询就自动从其关系表中获取数据???我真的根本不想使用查询生成器。

请提前致谢。

最佳答案

如果我很了解你,你需要获取方法EAGER

/**
* @OneToOne(targetEntity="Address")
* @JoinColumn(name="id_address", referencedColumnName="id", fetch="EAGER")
*/
   public $address

这样,每次您请求 User 时,您都会检索 Address 实体

关于php - Doctrine 2 : how to auto-get data of related tables?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37959537/

相关文章:

使用 PDO 更新 PHP

php - INSERT ON DUPLICATE KEY UPDATE 语句的复杂 mysql 查询错误

MYSQL ERROR 2049 (HY000) : Connection using old (pre-4. 1.1) 使用身份验证协议(protocol) ref(启用客户端选项 'secure_auth')

orm - 具有该实体外键的 Doctrine 实体

php - 用 Doctrine 查询语言写入 "NOT IN"

php - 干预/图像需要 FileInfo

MySQL 子查询总和与限制

c# - SQL连接字符串错误: Unable to connect to any of the specified MySQL hosts

Doctrine 2 : What is wrong with the association between these entities?

php - 从 php mysql 中的 csv 文件的标题中删除反斜杠 "\"