简体   繁体   中英

Doctrine query: best approach to creating a select query joining three tables?

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?

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(); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM