![](/img/trans.png)
[英]Laravel - Integrity constraint violation: 1452 Cannot add or update a child row
[英]Integrity constraint violation: 1452 Cannot add or update a child row:
我正在嘗試將值插入到我的評論表中,但出現錯誤。 它說我不能添加或更新子行,我不知道這意味着什么。
我的架構看起來像這樣
-- ----------------------------
-- Table structure for `comments`
-- ----------------------------
DROP TABLE IF EXISTS `comments`;
CREATE TABLE `comments` (
`id` varchar(36) NOT NULL,
`project_id` varchar(36) NOT NULL,
`user_id` varchar(36) NOT NULL,
`task_id` varchar(36) NOT NULL,
`data_type_id` varchar(36) NOT NULL,
`data_path` varchar(255) DEFAULT NULL,
`message` longtext,
`created` datetime DEFAULT NULL,
`modified` datetime DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `fk_comments_users` (`user_id`),
KEY `fk_comments_projects1` (`project_id`),
KEY `fk_comments_data_types1` (`data_type_id`),
CONSTRAINT `fk_comments_data_types1` FOREIGN KEY (`data_type_id`) REFERENCES `data_types` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `fk_comments_projects1` FOREIGN KEY (`project_id`) REFERENCES `projects` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `fk_comments_users` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf32;
-- ----------------------------
-- Records of comments
-- ----------------------------
-- ----------------------------
-- Table structure for `projects`
-- ----------------------------
DROP TABLE IF EXISTS `projects`;
CREATE TABLE `projects` (
`id` varchar(36) NOT NULL,
`user_id` varchar(36) NOT NULL,
`title` varchar(45) DEFAULT NULL,
`description` longtext,
`created` datetime DEFAULT NULL,
`modified` datetime DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `fk_projects_users1` (`user_id`),
CONSTRAINT `fk_projects_users1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf32;
-- ----------------------------
-- Records of projects
-- ----------------------------
INSERT INTO `projects` VALUES ('50dcbc72-3410-4596-8b71-0e80ae7aaee3', '50dcbc5c-d684-40bf-9715-0becae7aaee3', 'Brand New Project', 'This is a brand new project', '2012-12-27 15:24:02', '2012-12-27 15:24:02');
我試圖做的 mysql 語句看起來像這樣
INSERT INTO `anthonyl_fbpj`.`comments` (`project_id`, `user_id`, `task_id`, `data_type_id`, `message`, `modified`, `created`, `id`)
VALUES ('50dc845a-83e4-4db3-8705-5432ae7aaee3', '50dcbc5c-d684-40bf-9715-0becae7aaee3', '1', '50d32e5c-abdc-491a-a0ef-25d84e9f49a8', 'this is a test', '2012-12-27 19:20:46', '2012-12-27 19:20:46', '50dcf3ee-8bf4-4685-aa45-4eb4ae7aaee3')
我得到的錯誤看起來像這樣
SQLSTATE [23000]:完整性約束違規:1452不能添加或更新子行,外鍵約束失敗(
anthonyl_fbpj
。comments
,約束fk_comments_projects1
外鍵(project_id
)參考projects
(id
)ON DELETE NO ACTION ON UPDATE NO ACTION)
這只是意味着您插入的表comments
上的列project_id
的值在表projects
中不存在。 請記住,表comments
上的project_id
列的值取決於表Projects
上的ID
值。
您為列project_id
插入的值50dc845a-83e4-4db3-8705-5432ae7aaee3
在表projects
中不存在。
確保您的Comment
模型的fillable
屬性中有project_id
。
我有同樣的問題,這就是原因。
如果您向現有表添加新外鍵並且列不為空且未分配默認值,您將收到此錯誤,
您需要使其nullable
或assign default value
,或者delete all the existing records
來解決它。
還要確保您添加的外鍵與原始列的類型相同,如果您引用的列不是相同的類型,它也會失敗。
我希望我的決定會有所幫助。 我在 Laravel 中也有類似的錯誤。 我在錯誤的表中添加了外鍵。
錯誤的代碼:
Schema::create('comments', function (Blueprint $table) {
$table->unsignedBigInteger('post_id')->index()->nullable();
...
$table->foreign('post_id')->references('id')->on('comments')->onDelete('cascade');
});
Schema::create('posts', function (Blueprint $table) {
$table->bigIncrements('id');
...
});
請注意上面的 on('comments') 函數。 正確的代碼
$table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');
這意味着,對於列值project_id
表上comments
,你不僅將doesn't exist
於表項目,而且還project_id
可能沒有默認值。 例如,在我的情況下,我將其設置為 NULL。
對於 Laravel,您可以將此表達式視為遷移 php 文件的一段代碼,例如:
class ForeinToPhotosFromUsers extends Migration
{ /** * Run the migrations. * * @return void */
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->unsignedBigInteger('photo_id')->nullable();// ! ! ! THIS STRING ! ! !
$table->foreign('photo_id')->references('id')->on('photos');
});
}
}
顯然,您必須在所有這些旁邊創建 Model 類(在我的例子中是 Photo)。
首先刪除約束“fk_comments_projects1”及其索引。 之后重新創建它。
也許您想要創建 de FK 表中的一些行。
使用 foreign_key_checks OFF 運行遷移僅插入那些在內容表中具有相應 id 字段的記錄。
如果您沒有以正確的順序創建和填充表,您也會收到此錯誤。 例如,根據您的架構, Comments 表需要user_id
、 project_id
、 task_id
和data_type_id
。 這意味着Users
表、 Projects
表、 Task
表和Data_Type
表必須已經退出並在其中包含值,然后才能引用它們的 id 或任何其他列。
在 Laravel 中,這意味着以正確的順序調用數據庫播種機:
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*
* @return void
*/
public function run()
{
$this->call(UserSeeder::class);
$this->call(ProjectSeeder::class);
$this->call(TaskSeeder::class);
$this->call(DataTypeSeeder::class);
$this->call(CommentSeeder::class);
}
}
這就是我解決類似問題的方法。
如果有人正在使用 Laravel 並遇到此問題。 我也遇到了這個問題,問題出在我在數據透視表中插入 ID(即外鍵)的順序。
具體來說,請在下面找到多對多關系的示例:
wordtokens <-> wordtoken_wordchunk <-> wordchunks
// wordtoken_wordchunk table
Schema::create('wordtoken_wordchunk', function(Blueprint $table) {
$table->integer('wordtoken_id')->unsigned();
$table->integer('wordchunk_id')->unsigned();
$table->foreign('wordtoken_id')->references('id')->on('word_tokens')->onDelete('cascade');
$table->foreign('wordchunk_id')->references('id')->on('wordchunks')->onDelete('cascade');
$table->primary(['wordtoken_id', 'wordchunk_id']);
});
// wordchunks table
Schema::create('wordchunks', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->string('text');
});
// wordtokens table
Schema::create('word_tokens', function (Blueprint $table) {
$table->increments('id');
$table->string('text');
});
現在我的模型如下所示:
class WordToken extends Model
{
public function wordchunks() {
return $this->belongsToMany('App\Wordchunk');
}
}
class Wordchunk extends Model
{
public function wordTokens() {
return $this->belongsToMany('App\WordToken', 'wordtoken_wordchunk', 'wordchunk_id', 'wordtoken_id');
}
}
我通過交換 Wordchunk 模型中 'wordchunk_id' 和 'wordtoken_id' 的順序解決了這個問題。
對於代碼完成,這就是我堅持模型的方式:
private function persistChunks($chunks) {
foreach ($chunks as $chunk) {
$model = new Wordchunk();
$model->text = implode(' ', array_map(function($token) {return $token->text;}, $chunk));
$tokenIds = array_map(function($token) {return $token->id;}, $chunk);
$model->save();
$model->wordTokens()->attach($tokenIds);
}
}
當我不小心在我的子記錄中使用了錯誤的“uuid”時,我遇到了這個問題。 當這種情況發生時,約束會從子記錄到父記錄,以確保鏈接正確。 當我已經操縱我的模型來自動生成它時,我是手動生成的。 所以我的解決方法是:
$parent = Parent:create($recData); // asssigning autogenerated uuid into $parent
然后當我調用我的子類來插入子類時,我傳遞了這個 var 值:
$parent->uuid
希望有幫助。
我遇到了同樣的錯誤,問題是我試圖將role_id
外部添加到users
表中,但是role_id
沒有默認值,因此數據庫不允許我插入該列,因為我已經有一些用戶並且它不知道如何向他們添加列。 由於我在開發中,我只使用了migrate:fresh
,但如果我在生產中,我可能會為role_id
設置一個默認值,並且在我在數據庫上擁有相應的角色之前不會使其不受約束。
可能是您插入的外鍵值與主鍵的值不匹配。
問題可能是因為在您嘗試添加的具有 project_id 的數據庫中找不到項目記錄...
我有一張桌子,里面裝滿了一些帶有死外國人鑰匙的條目。 一旦我清理了桌子,我就能夠添加一個新的約束。
DELETE FROM `table_with_bad_entries` WHERE `expected_foreign_key` not in (select `id` from `the_referenced_table`);
就我而言,它不起作用,因為我在模型中的其中一個名稱中留了一個空格,請在此處輸入圖像描述
我只是導出刪除的表,然后再次導入它,它對我有用。 這是因為我刪除了父表(用戶),然后重新創建它,子表(喜歡)具有父表(用戶)的外鍵。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.