2017-09-04 56 views
0

我使用laravel-mongodbhttps://github.com/jenssegers/laravel-mongodb)MongoDB中操縱數據,laravel-mongodb:如何將外鍵添加到兩個現有集合?

我在MongoDB的兩個集合,它們是bookscategories

後來我將它們導入到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做到這一點,有什麼建議?

+0

你必須給每個條目不同的外鍵? – Sletheren

+0

@Sletheren我會將它們導入到mysql中,首先在MongoDB中操作它們。 – zwl1619

回答

1

嘗試這樣的:

$last_new_id = 1; 

foreach($categories as $category){ 
    $category->id = $last_new_id ; 
    $last_new_id++; 
} 

foreach($books as $book){ 
    $book->category_id = $categories->where('category',$book->category)->first()->id 
}