Sql FindOneBy或Find学说之间的分歧

Sql FindOneBy或Find学说之间的分歧,sql,symfony,doctrine,Sql,Symfony,Doctrine,有了条令,就可以通过一个ID进行查找,就像你想拥有关于一个用户的所有信息一样 您可以这样做: $em->getRepository(User::class)->findOneBy(数组('id'=>1)) 或者您可以这样做: $em->getRepository(User::class)->查找(1) 两者都给出相同的结果,但对于FindOneBy,您可以定义一个数组 如果你只想搜索一个ID,那有什么更好呢?为什么会更好(可能是因为性能)?使用findOneBy,您可以: ->findOn

有了条令,就可以通过一个ID进行查找,就像你想拥有关于一个用户的所有信息一样

您可以这样做: $em->getRepository(User::class)->findOneBy(数组('id'=>1))

或者您可以这样做: $em->getRepository(User::class)->查找(1)

两者都给出相同的结果,但对于FindOneBy,您可以定义一个数组


如果你只想搜索一个ID,那有什么更好呢?为什么会更好(可能是因为性能)?

使用findOneBy,您可以:

->findOneBy(['id' => 1, 'enabled' => true], ['createdAt' => 'DESC']);
否则,find是不使用db查询的首选方法

例如:

$swag = new Swag();
$swag->setSwagLevel(42);
$this->em->persist($swag); // Now you entity inside persistent collection, not in db.

$swag = $this->em->find(Swag::class, $swag->getId()) // Return entity from persistent collection, not from db in that case. Dump this $this->em->getUnitOfWork()->getScheduledEntityInsertions()


$user->giveSwag($swag);

$this->em->flush(); // Store all chain of changes to db.

谢谢你的回复。如果您在您的示例中使用find(…),它会更好地用于加载时间还是其他方面?我问这个问题是因为我正在和一个总是使用findOneBy的学生讨论,但是如果我只搜索ID,我更喜欢使用findOneBy。两者的执行时间不会有太大的差异。我认为当你想查找基于多个条件的结果时,
findOneBy
很有用。而
find
对于仅基于
id
查找结果非常有用。