Symfony中Entity设置OneToMany后保存数据的性能问题
有2个Entity,分别如下:
class Catogry {
/**
* @var int
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*
* @Serializer\Expose
*/
protected $id;
/**
* @ORM\OneToMany(targetEntity="Product", mappedBy="category")
*
* @Serializer\Exclude
*/
protected $products;
public function setProducts(ArrayCollection $products)
{
$this->products= $products;
return $this;
}
/**
* Get products.
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getProducts()
{
return $this->products;
}
/**
* Add product.
*
* @param Entity\Product $product
*
*/
public function addProduct(\Entity\Produc t$product)
{
if (!$this->products->contains($product)) {
$this->products[] = $product;
}
return $this;
}
/**
* Remove product.
*
* @param \Entity\Product $product
*/
public function removeProduct(\Entity\Product $product)
{
if ($this->products->contains($product)) {
$this->products->removeElement($product);
}
}
}
class Product {
/**
* @var int
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*
* @Serializer\Expose
*/
protected $id;
/**
* @var string
*
* @ORM\Column(name="title", type="string")
*
* @Serializer\Expose
*
* @Constraints\NotBlank()
*/
private $title;
/**
* @ORM\ManyToOne(targetEntity="Catogry", inversedBy="products")
* @ORM\JoinColumn(name="category_id", referencedColumnName="id", onDelete="SET NULL")
* @Serializer\Exclude
*/
private $category;
/**
* Get id.
*
* @return int
*/
public function getId()
{
return $this->id;
}
/**
* Get title.
*
* @return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set title.
*
* @param string $title
*
* @return mixed
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
public function setCategory($category)
{
$this->category= $category;
return $this;
}
public function getCategory()
{
return $this->category;
}
}
现在用下面语句添加product数据时,会发生性能问题:
$product = new Product();
$product->setTitle('test');
$category->addProduct($product);
$product->setCategory($category);
$manager = $this->getDoctrine()->getManager();
$manager->persist($category);
$manager->persist($product);
$manager->flush();
查看生成的sql语句有类似下面的语句:
SELECT
t0.id AS id1,
t0.category_id AS category_id2,
t0.title AS title3,
FROM
product t0
WHERE
t0.category_id = 1
消耗时间比较长,因为相关的数据有1w多条。
怎么处理这个问题呢?