dongtiao0657 2018-12-19 21:47
浏览 93

Doctrine查询:创建连接三个表的select查询的最佳方法?

I have three tables that I need to join to extract a result set, and I am not sure if I should use createQueryBuilder, createNativeQuery, or some other approach.

My three tables are

  • Email (joined to member via field: member)
  • Member (joined to company via field: current_company)
  • Company

The Entities are properly annotated in the code. For example In the Email Entity:

   /**
     * @ORM\ManyToOne(targetEntity="Member")
     * @ORM\JoinColumn(name="member", referencedColumnName="id", nullable=true)
     */
    protected $member;

In the Member Entity:

/**
 * @ORM\ManyToOne(targetEntity="Company")
 * @ORM\JoinColumn(name="current_company", referencedColumnName="id", nullable=true)
 */
protected $current_company;

And in the Company Entity:

/**
 * @ORM\ManyToMany(targetEntity="Member", mappedBy="companies")
 */
protected $members;

What I need to do is extract a set of records from Email where the Members are all associated with one Company.

The following SQL in MySQL returns what I need, but I am new to Doctrine and do not know how best to translate this query into something Doctrine can use to extract the same results:

select e.* from email e
join member m on m.id = e.member
join company c on c.id = m.current_company
where m.current_company = '95f1b5a4-03c9-11e9-85b1-989096db2d5f';

Can anyone help, and which approach should be employed createQueryBuilder, createNativeQuery, etc?

  • 写回答

1条回答 默认 最新

  • doudu7626 2018-12-20 18:07
    关注

    Update, I was able to get it working using plain old SQL, but I am not sure if this is an acceptable workaround in the Doctrine world. Thoughts and suggestions from those with more experience would be greatly welcome!

    $conn = $this->em->getConnection(); 
    $sql = "select e.* from fitchek.email e join fitchek.member m on m.id = e.member join fitchek.company c on c.id = m.current_company where m.current_company = ?"; 
    
    $stmt = $conn->prepare($sql); 
    $stmt->bindValue(1, $company_uuid); 
    $stmt->execute(); 
    
    评论

报告相同问题?

悬赏问题

  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)
  • ¥15 机器人轨迹规划相关问题
  • ¥15 word样式右侧翻页键消失