mySQL Insert失败:在Doctrine和Symfony 6.0中save()方法上UUID变为null.<



在过去的一个多小时里,我一直对这个bug摸不着头脑。我是Symfony项目(和Symfony一般)的新手,我们将数据存储在mySQL数据库中,我们的一些表在主键和外键字段中使用uuid作为id。

下面是项目中的一些示例代码:

public function createChannelHistory($consentParams, string $channelId, string $channelLabel): void
{
$channelHistory = new ChannelHistory();
$channelHistoryId = Uuid::v6();
$channelHistory->setId((string) $channelHistoryId);
$channelHistory->setChannelId($channelId);
$channelHistory->setLabel('Promotional ' . $channelLabel);
$channelHistory->setIsOptIn($consentParams[$channelLabel . '_opt_in']);
$channelHistory->setCreatedAt(new Carbon());
var_dump('channelId : ' . $channelId, 'channelHistoryId : ' .     $channelHistory->getId());

$this->channelHistoryRepository->save($channelHistory);
}

转储这两个变量会产生:"string(48) "channelId: 1ecec3c8-71aa-61be-8f38-2f921a413b0f"字符串(60)";///channelHistoryId: 1ecec3c8-71c8-6448-924f-2f921a413b0f"

然而,当到达保存方法时,似乎$channelId以某种方式被替换为null,并且插入失败,因为我们的channel_id列在表中被设置为NOT null。

dev.log文件包含:

[2022-06-15T01:51:26.554679+02:00] doctrine.DEBUG: Executing statement: INSERT INTO channel_history (id, channel_id, label, is_opt_in, created_at, created_by) VALUES (?, ?, ?, ?, ?, ?) (parameters: array{"1":"u001e���u�g������b?�","2":null,"3":"Promotional mail","4":0,"5":"2022-06-15 01:51:26","6":null}, types: array{"1":2,"2":2,"3":2,"4":5,"5":2,"6":2}) {"sql":"INSERT INTO channel_history (id, channel_id, label, is_opt_in, created_at, created_by) VALUES (?, ?, ?, ?, ?, ?)","params":{"1":"u001e���u�g������b?�","2":null,"3":"Promotional mail","4":0,"5":"2022-06-15 01:51:26","6":null},"types":{"1":2,"2":2,"3":2,"4":5,"5":2,"6":2}} []
[2022-06-15T01:51:26.560858+02:00] app.ERROR: An exception occurred while executing a query: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'channel_id' cannot be null

可以看到,在查询之前,两个变量都存在并且都是字符串类型,值与它们应该是的值相似。我不知道为什么第二个id在运行查询时变为空。

非常感谢你的帮助。

ChannelHistory和channelId是什么关系?如果Channel是一个实体,请查看有关ManyToOne和entity的文档,您应该传递实体的实例,而不是id。学说会处理的。

设置ChannelHistoryChannel的关联关系:

// src/Entity/ChannelHistory.php
namespace AppEntity;
// ...
class ChannelHistory
{
// ...
/**
* @ORMManyToOne(targetEntity="AppEntityChannel", inversedBy="histories")
*/
private $channel;
public function getChannel ?Channel
{
return $this->channel;
}
public function setChannel(?Channel $channel): self
{
$this->channel = $channel;
return $this;
}
}

那么你就可以将实体直接传递给函数和实体:

public function createChannelHistory($consentParams, Channel $channel, string $channelLabel): void
{
$channelHistory = new ChannelHistory();
// …
$channelHistory->setChannel($channel);
// …
}

相关内容

  • 没有找到相关文章

最新更新