Symfony主义LAZY数据加载

时间:2018-11-07 07:55:28

标签: symfony doctrine-orm lazy-loading

我想将一些数据传递给 JavaScript ,但是我却得到了空的vars

  

var testsCompany = {};

     

var testparams =“ [{}]”;

这与原则中的惰性数据加载有关,我尝试更改 ManyToOne 关联中的 fetch 属性值,但徒劳无功

这是我的代码:

  <script type="text/javascript">
    var testsCompany = "{{ testsCompany|json_encode()|raw}}";
    var testparams = "{{ testparams|json_encode()|raw}}";
  </script>

这是我的实体:

class TestParams
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * Many testparams have One test.
     * @ORM\ManyToOne(targetEntity="Tests", inversedBy="testparams",fetch="EAGER")
     * @ORM\JoinColumn(name="test_id", referencedColumnName="id")
     */
    private $test;


    /**
     * Many testparams have One param.
     * @ORM\ManyToOne(targetEntity="Params", inversedBy="testparams", fetch="EAGER")
     * @ORM\JoinColumn(name="param_id", referencedColumnName="id")
     */
    private $param;

    /**
     * @var bool
     *
     * @ORM\Column(name="required", type="boolean")
     */
    private $required;

    public function __construct()
    {
        $this->test = new ArrayCollection();
        $this->param = new ArrayCollection();
    }

    public function __toString()
    {
        return '*';
    }

}

这是控制器代码:

/**
     * @Route("/generate/{id}", name="prestashoptest_db_generate")
     */
    public function generateAction(Request $request)
    {
        $testId = $request->get('id');
        $testRepo = $this->getDoctrine()->getRepository('PrestaShopTestBundle:Tests');
        $testParamsRepo = $this->getDoctrine()->getRepository('PrestaShopTestBundle:TestParams');
        $testParams = $testParamsRepo->findBy(array("test" => $testId));
        $testsCompany = $testRepo->find($testId);

        return $this->render('PrestaShopTestBundle:BOTest:generate.html.twig',
            array(
                "testsCompany" => $testsCompany,
                "testParams" => $testParams,
            )
        );
    }

1 个答案:

答案 0 :(得分:0)

最后我有一个解决方案:

  1. 我安装了序列化器

    composer需要jms / serializer-bundle

  2. 配置它:

安装软件包后,只需将捆绑软件添加到AppKernel.php文件中即可:

new JMS\SerializerBundle\JMSSerializerBundle(),

  1. 并结合嫩枝助手:
 <script type="text/javascript">
 var testsCompany = {% autoescape %}{{ testsCompany|serialize|raw }}{% endautoescape %};
 var testParams =  {% autoescape %}{{  testParams|serialize|raw }}{% endautoescape %};
 </script>