如何从多个表中获取记录?

How to get records from multiple tables?

我有 3 个 MySQL 表,其中包含以下列:

table1: uid, name

table2: uid, color

table3: uid, car

uid列的值全部相同。我想从名称、颜色和汽车列中获取值,其中 uid = 5。

好吧,我可以使用:

$this->getDoctrine()->getRepository(Table1::class)->findOneBy(array('uid' => 5));
$this->getDoctrine()->getRepository(Table2::class)->findOneBy(array('uid' => 5));
$this->getDoctrine()->getRepository(Table3::class)->findOneBy(array('uid' => 5));

由于会有多个查询,这对性能不利。有没有办法只用一次查询就可以得到所有的记录?

您可以使用 queryBuilder 连接您的表,select 预期结果:

$queryBuilder
    ->select('t1.uid', 't1.name', 't2.color', 't3.car')
    ->from('table1', 't1')
    ->innerJoin('t1', 'table2', 't2', 't1.uid = t2.uid')
    ->innerJoin('t1', 'table3', 't3', 't1.uid = t3.uid')

您可以在此处找到更多信息:https://www.doctrine-project.org/projects/doctrine-dbal/en/2.9/reference/query-builder.html