PHP   发布时间:2022-04-09  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了php – Doctrine 2中的动态表/实体名称大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我希望有人可以了解我的代码发生了什么.

我需要一个表示通用表的实体作为具有X id后缀的表的模型.例如,我有一个实体:CustomerX
我需要查询的表是cusotmer_1,customer_2,customer_3 ……等等.

我目前正在使用:

class CustomerX {
/**
 * CustomerX
 *
 * @Table(name="customer_")
 * @Entity
 */


//..... properties and setters/getters....

private $_tableName = null;

public function getTableName() {
    return $this->_tableName;
}

public function setTableName($tableName) {
    $this->_tableName = $tableName;
    return $this;
}

public function loadClassMetadata(LoadClassMetadataEventArgs $eventArgs)
{
    $classMetadata = $eventArgs->getClassMetadata();

    $table = $classMetadata->table;
    $table['name'] = 'customer_'.$this->getTableName();
    $classMetadata->setPrimaryTable($table);
}


public static function getCustomerRecords($CustomerId) {
    $em = \Helper_Doctrine::em();

    $custTable = new \ME\CustomerX();
    $custTable->setTableName($CustomerId);
    $evm = $em->getEventManager();
    $evm->addEventListener(\Doctrine\ORM\Events::loadClassMetadata,$custTable);

    //get the customer info
    $query = $em->createQuery(
        'SELECT w
         FROM \ME\CustomerX w
         WHERE w.customerId = :CustId';
    $query->setParameter('CustId',$CustomerId);
    $custParams = $query->getResult();

    $evm->removeEventListener(\Doctrine\ORM\Events::loadClassMetadata,$custTable);
    $em->flush();

    return $custParams;
}

}

所以问题是,我可以在第一次获得客户时正确设置,但第二次,doctrine生成sql最终使用我创建的第一个表.

因此,如果我首先运行:CustomerX :: getCustomerRecords(‘123’),执行的sql和运行CustomerX :: getCustomerRecords(‘987′)的sql仍在使用’customer_123’.

我一定做错了什么.如果有人有任何关于如何正确删除或重置表名称的建议,那将是很好的.

谢谢.

我最初用这个作为参考.
Programmatically modify table’s schema name in Doctrine2?

问题很老,但对某人有帮助.

如果每次调用loadClassMetada,那么在您的代码中似乎存在问题.
但是,我想,元数据是由学说缓存的.
在这种情况下,您可以直接更改它,请查看以下代码片段,它应该工作:

<?PHP
class FooController extends Controller {
  function fooAction() {
    $em = $this->getDoctrine()->getEntityManager();
    $cm = $em->getClassMetadata('FooBundle:FooEntity');
    $cm->setTableName('special_table_name');
    $repo = $em->getRepository('FooBundle:FooEntity');
    $entities = $repo->createQueryBuilder('f')
            ->setMaxResults(1)
            ->orderBy('f.id','desc')
            ->getQuery()
            ->getResult();
    return new Response('');
  }
}

大佬总结

以上是大佬教程为你收集整理的php – Doctrine 2中的动态表/实体名称全部内容,希望文章能够帮你解决php – Doctrine 2中的动态表/实体名称所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: