Search

Oct 16, 2015

Yii: Get Data from table and mapping with other table or by condition Cdbcommand


// Get users Data on admin page
public function getAdminData() {
    $data = array();
    $conn = Yii::app()->db;
    $conn->active = true; // Start connect
    $cmdGetUser = $conn->createCommand();
    $cmdGetSession = $conn->createCommand();
    $cmdGetArchiveSession = $conn->createCommand();
    $cmdGetArchives = $conn->createCommand();

    // Get users
    $data['users'] = $cmdGetUser->select('*')
        ->from('users')
        ->query()
        ->readALl();

    // Get sessions
    $data['sessions'] = $cmdGetSession->select('s.*, u.username, count(i.idInvitedSession) as countUser')
        ->from('sessions s')
        ->join('users u','s.idUserCreate = u.idUser')
        ->join('invited_session i', 's.idSession = i.idSession')
        ->group('s.idSession')
        ->order('s.idSession DESC')
        ->query()
        ->readALl();

    // Get archives
    $data['archives'] = $cmdGetArchives->select('*')
        ->from('archives')
        ->order('archives.idArchive DESC')
        ->query()
        ->readALl();

    // Get Archive_session
    $data['archiveSession'] = $cmdGetArchiveSession->select('*')
        ->from('archive_session')
        ->order('archive_session.idArchive DESC')
        ->query()
        ->readALl();

    // Add sessions to archives by archive_session table
    foreach ($data['archives'] as $key => $subArchive) {
        $data['archives'][$key]['sessions'] = array();

        foreach ($data['archiveSession'] as $subArSes) {
            if ($subArSes['idArchive'] === $subArchive['idArchive']) {
                try {
                    $sData = Sessions::model()->findByPk($subArSes['idSession']);
                    array_push($data['archives'][$key]['sessions'], $sData );
                } catch (Exception $e) {
                    echo $e->getMessage(); exit;
                }
            }
        }
    }

    // Add sessions to users
    foreach ($data['users'] as $key => $subUser) {
        $data['users'][$key]['sessions'] = array();
        foreach ($data['sessions'] as $subSession) {
            if ($subSession['idUserCreate'] === $subUser['idUser']) {
                $sData = array(
                    'idTopic' => $subSession['idTopic'],
                    'title' => $subSession['title'],
                    'active' => $subSession['active']
                );
                array_push( $data['users'][$key]['sessions'], $sData);
            }
        }
    }

    $conn->active =  false; // Close connect
    return $data;
}

No comments:

Post a Comment