【问题标题】:Programmatically load Entity in symfony以编程方式在 symfony 中加载实体
【发布时间】:2018-03-27 01:11:42
【问题描述】:

我正在尝试加载实体类并在循环中使用,以便将内容从文件动态加载到相关表中。

有什么方法可以从以下加载所有实体文件

use AppBundle\Entity\aaPostcode;
use AppBundle\Entity\abPostcode;
use AppBundle\Entity\acPostcode;
use AppBundle\Entity\adPostcode;

以这样的方式?

use AppBundle\Entity\*

不确定这在 Symfony 中是否可行。

我的下一个问题是在这样的循环中使用 prefixedEntity -

new $entityPrefix

当我将 $entityPrefix 设置为以下格式时

$entityPrefix = str_replace([".csv"], "", $entityFilename) . "Postcode" . '()';

返回字符串的

"abPostcode()"

谁能告诉我为什么打电话

new $entityPrefix;

不工作

提前感谢您的帮助!

试图打电话

new $entityPrefix();

返回

[Symfony\Component\Debug\Exception\ClassNotFoundException]           
Attempted to load class "abPostcode" from the global namespace.      
Did you forget a "use" statement for "AppBundle\Entity\abPostcode"?  

即使我现在是人力资源部编码的使用语句来调用

use AppBundle\Entity\abPostcode;

【问题讨论】:

  • 你可以试试$entityPrefix = 'abPostcode'; 然后new $entityPrefix();
  • 感谢@kunicmarko20 已尝试此操作,但仍返回以下错误
  • 有问题的错误
  • 你不能这样做use AppBundle\Entity\*。我建议只加载适当的类$entityPrefix = "AppBundle\Entity\" . str_replace([".csv"], "", $entityFilename) . "Postcode";

标签: php symfony doctrine schema


【解决方案1】:

我在将数据从一种数据库类型迁移到另一种数据库类型时遇到了这个问题。 IE:Oracle 到 MySQL。如果有数百个表,使用部分会变得很大。

这是在 Symfony 5.2.x BTW 上。

当我使用标准存储库或链接到表的存储库运行查询时,我可以调用具有完整命名空间的实体。

$oracle = $em2->getRepository(\App\Entity\Oracle\Appoints::class)->Appoints();

所以我不必加载“使用 App\Entity\Oracle\Apppoints

然后我可以用同样的方法创建一个新对象:

$mysqlObject = new \App\Entity\OracleAppPoints();

【讨论】:

    【解决方案2】:

    我通过将功能提取到帮助程序中并根据输入运行 switch 语句来解决此问题 - 在本例中为 {prefix}

    【讨论】:

    • 怎么样?我不明白。
    【解决方案3】:

    如果没有完整的命名空间,你就不能动态地实例化你的类。试试看:

    $namespace = "AppBundle\Entity\\";
    $entityName = "YourEntity";
    $namespace .= $entityName;
    $class = new $namespace();
    

    这对我有用...

    【讨论】:

      猜你喜欢
      • 2011-02-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-02
      • 1970-01-01
      相关资源
      最近更新 更多