2012-04-28 43 views
1

我有兩個表格,tbl_studenttbl_record。我想加入他們,但我不知道如何在Yii中做到這一點。我使用的是PHP。我發現教程提CDbCriteria在Yii中加入表格

'join'=>"INNER JOIN...." 

我不知道什麼功能的代碼應該是什麼型號代碼應放置。 tbl_studentstud_id主鍵和tbl_recordrecord_id主鍵和stud_id作爲外鍵。有人能告訴我一步一步的過程嗎?

+2

你似乎不知道該怎麼做。我建議你更深入地學習yii。 – 2012-04-28 10:49:17

回答

9

請勿使用手動連接。使用Active Record可以更輕鬆地完成此操作。但是,給你整個「循序漸進的過程」並沒有像你想象的那樣真正讓你受益,你應該自己學習基礎知識,並提出具體的問題。 如果這個答案太混亂了,那麼Alfredo是對的,你應該花更多的時間在繼續之前學習框架。

步驟1:在各個型號中指定表格關係。如果你的數據庫架構使用外鍵(這是絕對應該),那麼gii模型生成器可以自動確定這些,否則你需要手動聲明它們:

/** 
* @property Record[] $records 
*/ 
class Student extends CActiveRecord { 
    // other code... 
    public function relations() { 
    return array(
     // other relations 
     array('records', self::HAS_MANY, 'Record', 'stud_id'), 
    ); 
    } 
} 

/** 
* @property Student $student 
*/ 
class Record extends CActiveRecord { 
    // other code... 
    public function relations() { 
    return array(
     // other relations 
     array('student', self::BELONGS_TO, 'Student', 'stud_id'), 
    ); 
    } 
} 

步驟2:使用活動記錄和管制員行動中的關係。這很大程度上取決於你想要做什麼。例如:加載單個學生的所有他/她的記錄。請注意,我直接在操作中打印數據 - 這是一個糟糕的主意,爲了簡潔起見,我在此僅使用它,但在真實應用程序中,您將希望使用此數據呈現視圖。

public function actionStudentInfo($id) { 
    $student = Student::model()->with('records')->findByPk($id); 
    if(!$student) { 
    throw new CHttpException(404, "Student not found!"); 
    } 
    echo "<h2>Found the requested student with details:</h2>", 
    "<pre>", htmlspecialchars(print_r($student->attributes, true)), "</pre>"; 
    if(count($student->records)) { 
    echo "<h3>Student records:</h3>", "<ul>"; 
    foreach($student->records as $record) { 
     echo "<li><pre>", htmlspecialchars(print_r($record->attributes, true)), "</pre></li>"; 
    } 
    echo "</ul>"; 
    } else { 
    echo "<p>Student has no records...</p>"; 
    } 
} 

這個關鍵部分是->with('records')調用。它告訴Active Record系統在查詢中包含學生模型的records關係數據。 Active Record將讀取該關係並將其包含在查詢中並返回結果 - StudentRecords將在$student->records(這將是一個數組)中可用。

您可以在關係規範中包含很多額外的細節,例如,現在它將以特定順序提取這些記錄,如果要強制排序,則可以指定'order' => 'field_name ASC'

活動記錄的用法在Yii文檔中有更詳細的介紹:Active Record,Relational Active Record