gpt4 book ai didi

php - Symfony - 为多对多关系创建的表构建查询

转载 作者:行者123 更新时间:2023-11-29 10:50:15 33 4
gpt4 key购买 nike

我有 2 个实体通过多对多关系连接到第三个表中,我想获取产品 id 的每种颜色:

/**
* @var ArrayCollection
*
* @ORM\ManyToMany(targetEntity="AppBundle\Entity\Color", inversedBy="products")
* @ORM\JoinTable(name="products_colors",
* joinColumns={@ORM\JoinColumn(name="product_id", referencedColumnName="id")},
* inverseJoinColumns={@ORM\JoinColumn(name="color_id", referencedColumnName="id")}
* )
*/
private $colors;

在我的第二个实体中:

/**
* @var ArrayCollection
*
* @ORM\ManyToMany(targetEntity="AppBundle\Entity\Product", mappedBy="colors")
*/
private $products;

这是我的查询:(我试图进行一些连接,但无法使其工作)

class ProductRepository extends \Doctrine\ORM\EntityRepository
{
public function getColors($id)
{
$query = $this->createQueryBuilder('p')
->join('AppBundle\Entity\Color', 'c')
->where('c.product_id = :id')
->setParameter('id', $id)
->getQuery()
->getResult();

return $query;
}
}

我收到此错误:

[Semantical Error] line 0, col 85 near 'product_id =': Error: Class AppBundle\Entity\Color has no field or association named product_id

我明白,但想不出一种方法来实现这一点。

最佳答案

Symfony 希望您在通过 ManyToMany 关系映射时引用对象的实体(而不是 id)。尝试:

class ProductRepository extends \Doctrine\ORM\EntityRepository
{
public function getColors(Product $product)
{
$query = $this->createQueryBuilder('p')
->join('AppBundle\Entity\Color', 'c')
->where('c.product = :product')
->setParameter('product', $product)
->getQuery()
->getResult();

return $query;
}
}

当然,您必须相应地修改对此函数的调用。

您还可以使用实体中的 getter 函数来完全跳过查询创建; symfony 会自动为您执行查询。

// class Product

private $colors; // as you have it set up already

/**
* @return ArrayCollection|Color[]
*/

public function getColors()
{
return $this->colors;
}

关于php - Symfony - 为多对多关系创建的表构建查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43857709/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com