2013-04-16 57 views
1

我有一個數據庫與兩個集合。學生館藏有一個名爲「student_bookselections」的字段,用於保存書籍的ID。該字段的內容通常會被更改或更新。我們如何更新學生選擇?

  1. 我們如何添加或刪除id到student_bookselections?
  2. 這是一個體面的方式來關聯集合?

學生收集

   array(
       "student_id" => 4, 
       "student_fullname" => $studentfullname, 
       "student_bookselections" => 'id1, id34, id788 ... ... id4' 

       ) 

藏書

   array(
       "book_id" => 4354, 
       "book_title" => $title, 
       "book_author" => $author, 

       ) 
+0

? –

+0

@ S.Visser:是的,我正在使用mongodb,但我是一個newby – mustafa

回答

0

要更新

<?php 

    $mongo = new Mongo(); 
    $db = $mongo->selectDB("Your_Database"); 

    $student = $db->students; 

    $update = array("$set" => array("student_bookselections" => "your ids")); 
    $where = array("student_id" => 4); 
    $student->update($where,$update); 

?> 

要插入

<?php 

    $mongo = new Mongo(); 
    $db = $mongo->selectDB("Your_Database"); 

    $student = $db->students; 

    $insert = array("student_fullname" => "Stefan", "student_bookselections" => "your ids"); 
    $student->insert($insert); 

?> 

要刪除

<?php 

    $mongo = new Mongo(); 
    $db = $mongo->selectDB("Your_Database"); 

    $student = $db->students; 

    $student->remove(array("ID" => 4)); 

?> 

關係 (請參閱從Crhis後)

Users(
    "student_id" => 4, 
    "student_fullname" => $studentfullname 
) 

Books(
    "book_id" => 4, 
    "book_title" => $title, 
    "book_author" => $author 
) 

Selections(
    "selection_id" => 4, 
    "student_id" => $studentid, 
    "book_id" => $bookid 
) 

選擇帶有使用權的MongoDB這種關係

<?php 

    $mongo = new Mongo(); 
    $db = $mongo->selectDB("Your_Database"); 

    $selection = $db->selections; 

    $res = $student->find(array("student_id" => $student_id)); 

?> 
+0

假設student_selections包含id 1,2,3,4,5。所以我想刪除2並將9添加到列表中。你的代碼是這樣做的嗎? – mustafa

+0

@Mustafa,因爲你真的需要改變你的數據庫結構。因爲否則你自己真的很難。 –

+0

所以你建議選擇一個新的集合 - 我想保持他們在學生收藏。因爲在學生館藏中選擇內容比搜索相對龐大的單獨館藏更容易。我錯了嗎? – mustafa

1

你會好起來的具有第三表給學生鏈接到書,你當前的實現不歸。

Users(
    "student_id" => 4, 
    "student_fullname" => $studentfullname 
) 

Books(
    "book_id" => 4, 
    "book_title" => $title, 
    "book_author" => $author 
) 

Selections(
    "selection_id" => 4, 
    "student_id" => $studentid, 
    "book_id" => $bookid 
) 

然後,您可以定義與外鍵關係,鏈接表,更重要的是每一行與一條信息。如果你想知道某個學生的所有書籍選擇

mysql_query("SELECT * FROM Selections WHERE student_id = $student_id"); 

希望幫助!

+0

他使用'mongodb';) –

+0

但是結構是正確的。 –

+0

啊道歉沒有看到蒙古,不理我的插入。將我對新表格的建議與其他答案中的有用代碼結合起來,我認爲你會有一個很好的解決方案。 – Chris