我正在使用 laravel 将一些内容从远程 WP 数据库导入到本地数据库。我已经设置了表格库存和内容。
库存表如下所示:
Schema::create('inventories', function (Blueprint $table) {
$table->increments('id');
$table->integer('remote_id')->unsigned();
$table->integer('local_id')->unsigned();
$table->string('local_type');
$table->timestamps();
$table->foreign('local_id')->references('id')->on('contents')->onDelete('cascade');
});
这是目录:
Schema::create('contents', function (Blueprint $table) {
$table->increments('id')->unsigned();
$table->integer('ct_id')->unsigned();
$table->foreign('ct_id')->references('id')->on('content_types');
$table->integer('cms_id');
$table->string('title');
$table->string('slug');
$table->text('excerpt');
$table->mediumText('body');
$table->string('password');
$table->integer('parent_id');
$table->timestamps();
});
我已经创建了从远程 WP DB 导入所有帖子和导入单个帖子的功能。这是所有帖子的导入:
public function all()
{
$include = array_diff($this->indexable, ['folder']);
$publishedPostsIDs = $this->import($include);
$this->deleteOldContent($publishedPostsIDs);
}
private function import($include)
{
$posts = Post::where('post_status', 'publish')->whereIn('post_type', $include)->get();
foreach ($posts as $post) {
$publishedPostsIDs[] = $post->ID;
$this->contentInterface->updateOrCreateInventory($post->ID);
}
return $publishedPostsIDs;
}
public function updateOrCreateInventory($remoteId)
{
$this->contentInterface->updateOrCreateInventory($remoteId);
}
private function deleteOldContent($publishedPostsIDs)
{
$contentToDelete = Content::whereNotIn('cms_id', $publishedPostsIDs)->get();
if (count($contentToDelete) > 0) {
foreach ($contentToDelete as $content) {
$content->delete();
}
}
}
因此,当我导入所有内容时,我只需转到前往
all
功能的路线,并且所有来自远程 WP DB 的非帖子类型文件夹的帖子都会被导入。如果我想从远程数据库导入单个帖子,那么我有一条直接通往 updateOrCreateInventory
函数的路线。我还导入了文件夹类型的帖子,基本上和功能几乎一样all
。
public function folder()
{
$include = ['folder'];
$importResult = $this->import($include);
return $importResult['imported'];
}
我遇到的问题是,当我一次导入所有文件夹时,出现错误:
Connection.php 第 729 行中的 QueryException:SQLSTATE[23000]:完整性 违反约束:1452 无法添加或更新子行:外部 键约束失败 (但是,如果我尝试单独导入相同的文件夹,或者更确切地说,导入类型文件夹的相同帖子,我不会收到任何错误,并且帖子会被导入。这怎么可能?
middleton
.inventories
, CONSTRAINTinventories_local_id_foreign
外键 (local_id
) 参考contents
(id
) 删除级联)(SQL:插入inventories
(remote_id
,updated_at
,created_at
) 值 (7512, 2017-11-13 15:33:17, 2017-11-13 15:33:17))
找到创建 Inventory 模型的位置并提供有效的“local_id”。