我正在使用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中不属于post类型文件夹的所有帖子。如果我想从远程数据库导入单个帖子,那么我有一条直接转到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
FOREIGN KEY(local_id
)参考contents
(id
)ON DELETE CASCADE)(SQL:插入inventories
(remote_id
,updated_at
,created_at
)值(7512,2017-11-13 15:33:2017,2017-11-13 15:33:17))
但是,如果我尝试单独导入相同的文件夹,或者更准确地导入类型文件夹的相同帖子,我不会收到任何错误并导入帖子。怎么可能?
答案 0 :(得分:0)
你$ this-> contentInterface创建一个没有" local_id"的库存模型。指定的字段,但外键需要它。
找到您创建广告资源模型的位置,并提供有效的" local_id"。