0

という名前の db テーブルがStudentあり、列はid, name,ageです。 idは主キーでnameあり、null ではなく、null にageすることができます

PHP、Zendで次を実装したい: 値が異なる場合にのみ、dbに重複した学生を追加します。nameage

function/action 内でaddStudentAction、 Student モデルの関数を呼び出してfindStudent、要件を実装します。

public function findStudent($name)
{
    $result = null;

    $select = $this->select(Zend_Db_Table::SELECT_WITH_FROM_PART)
    ->setIntegrityCheck(false)
    ->where('student.name = ?', $name);

    //error_log($select->assemble());

    $result = $this->getAdapter()->fetchRow($select);

    return $result;
}

public function addStudentAction() {
    $data = $_POST;
    $studentModel = new Application_Model_Student;
    $result = $studentModel->findStudent($data['name']);

    if(!empty($result)) { 
        error_log("found student name in db, going to get age");

       //Check for age
       if( (!empty($result['age'] )) {
             if( $result['age'] != $data['age']) {
                  error_log("going to add student as new record");
                  return $this->insert($data);
             }
             else {
                  error_log("not adding new student record ");
             }
       }
    }
}

ここで、値は同じだが値が異なる複数の学生のレコードが存在する可能性があります。nameageしたがって、新しい学生を追加するときは、すべてのレコードの年齢 (名前が一致する場合) を年齢の受信値と比較する必要があります。

この要件を実装する最善の方法は何ですか? どんな助けでも大歓迎です。

ありがとう

4

2 に答える 2

0

最も簡単な方法は、名前、次に年齢フィールドに複合 UNIQUE インデックスを作成することです。UNIQUE は複数の NULL 値を許可するため、問題にはなりません。データベースのサイズと使用状況によっては、これが最も好ましいオプションではない場合があります。その場合、INSERT の前に学生情報の単純な SELECT を実行して、学生がすでにそこにいるかどうかを確認するのが最善の解決策です。

これについて詳しく説明する必要がある場合はお知らせください。いくつか例を挙げていただければ幸いです。

于 2012-07-10T01:30:58.733 に答える
0

名前と年齢で新しい SELECT を実行してみませんか。

public function findStudentWithAge($name, $age =null)
{
    $result = null;

    $select = $this->select(Zend_Db_Table::SELECT_WITH_FROM_PART)
    ->setIntegrityCheck(false)
    ->where('student.name = ?', $name);
    if($age) $select->where('student.age = ?', $age);

    //error_log($select->assemble());

    $result = $this->getAdapter()->fetchRow($select);

    return $result;
}

addStudentAction で:

public function addStudentAction() {
    $data = $_POST;
    $studentModel = new Application_Model_Student;
    $result = $studentModel->findStudent($data['name'], $data['age']);

    if(!empty($result)) { 
        error_log("found student with this age, cannot add the record");
    } else {
        $this->insert($data);
    }
}
于 2012-07-10T12:30:19.427 に答える