我有一个Product实体,与另一个与manyToOne关联的User实体相关

class Product implements AuthoredEntityInterface
{
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;

/**
* @ORM\ManyToOne(targetEntity="App\Entity\User", inversedBy="products")
* @ORM\JoinColumn(nullable=false)
*/
private $user;

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

/**
* @ORM\Column(type="double")
*/
private $price;

//various getters and setters

}

AuthoredEntityInterface有助于将用户设置为当前登录的用户。当我对/api/products(我使用 postman )进行api调用时,传递的json如下所示:
{
    "name": "my product",
    "price": 10
}

这将起作用,并创建一个新记录。问题出在单元测试上。我打这样的电话:
$headers = [
        'HTTP_AUTHORIZATION' => 'Bearer ' . $token,
        'CONTENT_TYPE' => 'application/ld+json',
        'HTTP_ACCEPT' => 'application/ld+json'
    ];
$postData = [
    'name' => 'my product',
    'price' => 10
];
$client = $this->makeClient();
    $client->request('POST', '/api/products', [], [], $headers, json_encode($postData));

我收到此错误:
提供了无效的值(无效的IRI?)

现在,唯一提到的IRI应该是用户,如上所述,它是在类内部自动生成的。

任何想法?

更新:

填充用户字段

产品中的方法
public function setUser(UserInterface $user): AuthoredEntityInterface
{
    $this->user = $user;
    return $this;
}

然后,我使用事件订阅者:
class AuthoredEntitySubscriber implements EventSubscriberInterface
{
/** @var TokenStorageInterface */
private $tokenStorage;

public function __construct(TokenStorageInterface $tokenStorage)
{
    $this->tokenStorage = $tokenStorage;
}

public static function getSubscribedEvents()
{
    return [
        KernelEvents::VIEW => ['getAuthenticatedUser', EventPriorities::PRE_WRITE]
    ];
}

public function getAuthenticatedUser(GetResponseForControllerResultEvent $event)
{
    $entity = $event->getControllerResult();
    $method = $event->getRequest()->getMethod();

    /** @var UserInterface $user */
    $user = $this->tokenStorage->getToken()->getUser();

    if((!$entity instanceof AuthoredEntityInterface) || Request::METHOD_POST != $method) {
        return;
    }

    $entity->setUser($user);
}
}

最佳答案

您必须将$postData编码为所需的内容类型,例如。 JSON,并且必须将编码后的数据传递到$client->request()

10-07 22:01