【发布时间】:2018-02-12 20:32:06
【问题描述】:
我正在使用laravel-mongodb(https://github.com/jenssegers/laravel-mongodb) 来操作mongodb中的数据,
我在 mongoDB 中有两个集合,它们是 books 和 categories。
稍后我会将它们导入mysql,所以我想先将它们与外键关联起来。
从 mongodb 获取它们:
public function getBooksAndCategories()
{
$books = DB::connection('mongodb')->collection('books')->get();
$categories = DB::connection('mongodb')->collection('categories')->get();
}
它们看起来像这样:
$books = collect([
['_id' => 'xxx','name' => 'history book 1', 'category' => 'history'],
['_id' => 'xxx','name' => 'history book 2', 'category' => 'history'],
['_id' => 'xxx','name' => 'science book 1', 'category' => 'science'],
['_id' => 'xxx','name' => 'science book 2', 'category' => 'science'],
['_id' => 'xxx','name' => 'sociology book 1', 'category' => 'sociology'],
['_id' => 'xxx','name' => 'sociology book 2', 'category' => 'sociology'],
['_id' => 'xxx','name' => 'economics book 1', 'category' => 'economics'],
]);
$categories = collect([
['_id' => 'xxx','category' => 'history'],
['_id' => 'xxx','category' => 'science'],
['_id' => 'xxx','category' => 'sociology'],
['_id' => 'xxx','category' => 'economics'],
]);
首先,我需要在$categories中添加一个id,结果是这样的:
$newCategories = collect([
['_id' => 'xxx','category' => 'history','id' => 1],
['_id' => 'xxx','category' => 'science','id' => 2],
['_id' => 'xxx','category' => 'sociology','id' => 3],
['_id' => 'xxx','category' => 'economics','id' => 4],
]);
其次,我需要在集合$books中添加一个外键,结果是这样的:
$newBooks = collect([
['_id' => 'xxx','name' => 'history book 1', 'category' => 'history','category_id' => 1],
['_id' => 'xxx','name' => 'history book 2', 'category' => 'history','category_id' => 1],
['_id' => 'xxx','name' => 'science book 1', 'category' => 'science','category_id' => 2],
['_id' => 'xxx','name' => 'science book 2', 'category' => 'science','category_id' => 2],
['_id' => 'xxx','name' => 'sociology book 1', 'category' => 'sociology','category_id' => 3],
['_id' => 'xxx','name' => 'sociology book 2', 'category' => 'sociology','category_id' => 3],
['_id' => 'xxx','name' => 'economics book 1', 'category' => 'economics','category_id' => 4],
]);
我不知道如何使用laravel-mongodb,有什么建议吗?
【问题讨论】:
-
你必须给每个条目一个不同的外键吗?
-
@Sletheren 我将它们导入 mysql,首先在 mongodb 中操作它们。