1.2Symfony模型(Doctrine)之记录(Record)

查询

//初始化$entityManager并生成$productRepository
$entityManager = $this->getDoctrine()->getManager();
$productRepository = $entityManager->getRepository(Product::class);
//简写
$productRepository = $this->getDoctrine()->getRepository(Product::class);
// 按主键查询单个对象
$product = $productRepository->find($id);

// 按字段查询单个对象
$product = $productRepository->findOneBy([
    'name' => 'Keyboard',
    'price' => 1999,
]);

// 按字段查询所有符合条件的对象
$products = $productRepository->findBy(
    ['name' => 'Keyboard'],
    ['price' => 'ASC']
);

// 查询所有对象
$products = $repository->findAll();

新增

//初始化$entityManager
$entityManager = $this->getDoctrine()->getManager();

//初始化$product
$product = new Product();
$product->setName('Keyboard');
$product->setPrice(1999);
$product->setDescription('Ergonomic and stylish!');

//$entityManager持久化操作$product
$entityManager->persist($product);

//让操作同步到到数据库
$entityManager->flush();

更改

//初始化$entityManager
$entityManager = $this->getDoctrine()->getManager();

//查询$product
$product = $entityManager->getRepository(Product::class)->find($id);
$product->setName('New product name!');

//(此步骤可省略)$entityManager持久化操作$product
$entityManager->persist($product)

//让操作同步到到数据库
$entityManager->flush();

删除

//初始化$entityManager
$entityManager = $this->getDoctrine()->getManager();           

//查询$product
$product = $entityManager->getRepository(Product::class)->find($id);

//$entityManager删除操作$product
$entityManager->remove($product);

//让操作同步到到数据库
$entityManager->flush();

原创文章,作者:huoxiaoqiang,如若转载,请注明出处:https://www.huoxiaoqiang.com/php/symfony/6318.html

发表评论

登录后才能评论