简体   繁体   English

Doctrine - 当主键不等于外键时如何获取记录

[英]Doctrine - How to get the records when primary key is NOT equal to foreign key

I'm learning Doctrine by making Symfony application and I have a problem with my code.我正在通过制作 Symfony 应用程序来学习 Doctrine,但我的代码有问题。 I'm trying to get all records from flashcards table except for those that are placed inside trash table.我正在尝试从抽认flashcards表中获取所有记录,除了那些放在trash表中的记录。 In other words I need those flashcards which not exist in trash table.换句话说,我需要那些trash表中不存在的抽认卡。

trash and flashcards are related with one-to-one relation. trashflashcards是一对一的关系。 The flashcards's primary key is the trash's foreign key so I tried something like this: flashcards's主键是trash's外键,所以我尝试了这样的事情:

$qb = $this->createQueryBuilder('f');
$expr = $qb->expr();

$query = $qb
    ->join('f.trash', 't')
    ->andWhere($expr->neq('t.flashcard', 'f.id'))
    ->getQuery()
    ->getResult();

The query is executed properly, there's no errors but also there's no returned records.查询执行正确,没有错误但也没有返回记录。

Could you write, please, why this ORM code doesn't return any records and could you give me some tips how to make it working?请你写一下,为什么这个 ORM 代码不返回任何记录,你能给我一些提示如何使它工作吗?

Thanks in advance for every answer!提前感谢您的每一个答案!

What you need is an OUTER JOIN (which you will not find in the Doctrine but keep reading):您需要的是 OUTER JOIN(在 Doctrine 中找不到,但请继续阅读):

外连接

Where Table A = flashcards, Table B = trash;其中表 A = 抽认卡,表 B = 垃圾;

Example Query to get that:示例查询以获取:

SELECT * FROM TableA
LEFT OUTER JOIN TableB
ON TableA.name = TableB.name
WHERE TableB.id IS null

more read on possible joins and their queries 更多阅读可能的连接及其查询

Using Doctrine does not force you to use its queryBuilder , you can use a plain SQL with Docktrine as well.使用 Doctrine 不会强迫您使用它的queryBuilder ,您也可以将普通的 SQL 与 Docktrine 一起使用。

All what you need is to build query on your own and execute it with Doctrine connection as in documentation :您需要做的就是自己构建查询并使用 Doctrine 连接执行它,如文档中所示:

use Doctrine\DBAL\DriverManager;

$conn = DriverManager::getConnection($params, $config);

$sql = "SELECT * FROM articles";
$stmt = $conn->query($sql);

There are no RIGHT JOINs, nor OUTER JOINs in Doctrine, my guess is that it is due to the nature of the project which is simplicity and more importantly a portability. Doctrine 中没有 RIGHT JOIN,也没有 OUTER JOIN,我猜这是由于项目的性质,它很简单,更重要的是可移植性。

Perhaps this question will also help you somehow if you want to give the query builder the last try.如果您想最后一次尝试查询生成器,也许这个问题也会以某种方式帮助您。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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