将实体声明为另一个实体,获取要在产品类别上设置的类别名称

Declaring Entity to another Entity, get category name to be set on product category

我很困惑。

我有一个 ProductRepository.php 管理所有产品,然后我有一个 category 属性应该连接到 CategoryRepository.php 或类别实体。

这是我在 ProductRepository.php

中的代码
namespace App\Repository;

use App\Entity\Product;
use App\Entity\Category;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Symfony\Bridge\Doctrine\RegistryInterface;

class ProductRepository extends ServiceEntityRepository
{
    public function __construct(RegistryInterface $registry)
    {
        parent::__construct($registry, Product::class);
    }

    public function transform(Product $product)
    {
        $category = Category($product->getCategory()); // error
        $category = $category->getName();

        return [
                'id'    => (int) $product->getId(),
                'name' => (string) $product->getName(),
                'category' => (int) $product->getCategory(),
                'category_name' => (string) $category,
                'SKU' => (string) $product->getSKU(),
                'price' => (float) $product->getPrice(),
                'quantity'    => (int) $product->getQuantity()
        ];
    }

我的问题是,我在声明类别 class 时出错,对此有任何想法吗? 我的目标是从产品的类别属性中获取 category name,即 category model

id

类别模型是:

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass="App\Repository\CategoryRepository")
 */
class Category
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $name;

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getName(): ?string
    {
        return $this->name;
    }

    public function setName(string $name): self
    {
        $this->name = $name;

        return $this;
    }
}

我想我明白你想做什么。

假设 Product::category 是产品和类别 类 之间的关系:

 $categoryName = $product->getCategory()->getName();

您只需获取对象类别,然后获取其名称。