为什么在我的测试中无法建立合作关系?例如,一个产品有两个ProductVariant,但是$ product-> getVariants()-> count()返回0,但是count($ variants)返回2。
<?php
namespace App\Tests\Service\Marketplace\Banggood;
use App\Test\TestCase;
use Nelmio\Alice\Loader\NativeLoader;
class ImportOrderTest extends TestCase
{
public function test_transform()
{
$this->loadFixtures();
$product = $this->getEntityManager()->getRepository('App:Product')->findOneBy(['foreignId' => 93255]);
$variants = $this->getEntityManager()->getRepository('App:ProductVariant')->findBy(['product' => $product]);
dd($product->getVariants()->count(), count($variants));
}
protected function getEntityManager()
{
return $this->getService('doctrine.orm.entity_manager');
}
protected static function getService($id)
{
return self::$kernel->getContainer()->get($id);
}
protected function loadFixtures()
{
$loader = new NativeLoader();
$objectSet = $loader->loadFile(__DIR__."/../DataFixtures/test/fixtures.yaml");
foreach ($objectSet->getObjects() as $entity)
{
$this->getEntityManager()->persist($entity);
}
$this->getEntityManager()->flush();
}
我花了大约4个小时,但没有发现错误所在。
fixtures.yaml
App\Entity\Product:
product:
name: 'Product # 1'
foreignId: <numberBetween(1,99999)>
bodyHtml: <text(300)>
description: '<paragraph(1)>'
tags: ''
option1: "Size"
option2: "Color"
App\Entity\ProductVariant:
pv{1..2}:
product: '@product'
name: 'Variant <current()>'
grams: <numberBetween(100, 1000)>
sku: <ean8()>
option1 (unique): <numberBetween(1, 200)>
option2: "<randomElement(['red', 'yellow', 'black', 'green', 'white'])>"
我的灯具工作正常,在数据库中,我在product表中看到一行,在product_variants表中看到两行。
App \ Entity \ Product类中的片段
/**
* @ORM\OneToMany(targetEntity="App\Entity\ProductVariant", mappedBy="product", orphanRemoval=true, cascade={"persist"})
*/
private $variants;
/**
* @return Collection|ProductVariant[]
*/
public function getVariants(): Collection
{
return $this->variants;
}
答案 0 :(得分:0)
我发现了这个错误,它在我的装置中。以下代码的正确变体。
amp-ima-video