在過去的一個小時左右,我一直在為這個錯誤撓頭。我是 Symfony 專案(以及一般的 Symfony)的新手,我們將資料存盤在 mySQL 資料庫中,我們的一些表在主鍵和外鍵欄位中都使用 UUIDS 作為 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“string(60)”///channelHistoryId:1ecec3c8-71c8-6448-924f-2f921a413b0f“”。
但是,當到達 save 方法時,似乎 $channelId 以某種方式被替換為 null,并且插入失敗,因為我們在 table 中的 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 變為空。
幫助將不勝感激。
uj5u.com熱心網友回復:
ChannelHistory 和 channelId 是什么關系?如果 Channel 是物體,請查看有關ManyToOne 和 entity的檔案,您應該傳遞物體的實體,而不是 id。教義會處理它。
設定 和 之間的ChannelHistory關聯Channel:
// src/Entity/ChannelHistory.php
namespace App\Entity;
// ...
class ChannelHistory
{
// ...
/**
* @ORM\ManyToOne(targetEntity="App\Entity\Channel", 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);
// …
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/491474.html
