0
我使用laravel-mongodb
(https://github.com/jenssegers/laravel-mongodb)MongoDB中操纵数据,laravel-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'],
]);
第一,我需要添加一个id
到$categories
,结果是这样的:
$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
@Sletheren我会将它们导入到mysql中,首先在MongoDB中操作它们。 – zwl1619