FindOneBy或Find Doctrine之间的差异

时间:2018-08-20 08:56:07

标签: sql symfony doctrine

使用Doctrine可以通过ID查找,就像您想获取有关用户的所有信息一样。

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

或者您可以执行以下操作: $ em-> getRepository(User :: class)-> find(1);

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

如果您只想搜索ID,该怎么办?以及为什么它会更好(性能表现很糟糕)?

1 个答案:

答案 0 :(得分:1)

使用findOneBy,您可以:

->findOneBy(['id' => 1, 'enabled' => true], ['createdAt' => 'DESC']);

否则,find是无需数据库查询的首选工作方式。

例如:

$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.