0

I am using the following code to get the 5 most active user id.

 public function actionAllstats()
            {

        $this->layout='main';
        $user=UserJoinEvent::model()->findAll(array(//yeh hum model isi query mein chala raya hain because jab mein ne
                                                    //yeh $rbmodel=userjoinevent::model->findall() se kia tha to yeh mujhay saray results userjoinevent ke show raha 
                                                    //tha, matlab sari user_id of this table show kar raha tha
                'select'=>'user_id',
                'group'=>'user_id',
                'order'=>'COUNT(*) DESC',
                'limit' =>  5
             ));  
        $this->render('allstats', array("user"=>$user));
            } 

and the view file is

<div>
        <?php
            foreach($user as $show)
            {
                echo '<h3>' . $show->user_id . '</h3>';
            }
        ?>
    </div>

How can i get the names of the users againt their id, the name is from the User model. This is the code for the user model

<?php

/**
 * This is the model class for table "user".
 *
 * The followings are the available columns in table 'user':
 * @property integer $id
 * @property string $username
 * @property string $password
 * @property string $email
 * @property string $gender
 * @property string $activkey
 * @property string $create_at
 * @property string $lastvisit_at
 * @property integer $superuser
 * @property integer $status
 * @property string $salt
 * @property integer $requires_new_password
 * @property integer $login_attempts
 * @property integer $login_time
 * @property string $login_ip
 * @property string $activation_key
 * @property string $validation_key
 * @property string $create_time
 * @property string $update_time
 * @property string $reset_token
 * @property string $image
 * @property string $address
 *
 * The followings are the available model relations:
 * @property UserJoinEvent[] $userJoinEvents
 * @property UserRateReviewNgo[] $userRateReviewNgos
 * @property UserUploadVideo[] $userUploadVideos
 * @property UserWriteStory[] $userWriteStories
 * @property VolunteerForm[] $volunteerForms
 */
class User extends CActiveRecord
{
    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return User the static model class
     */
    public static function model($className=__CLASS__)
    {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName()
    {
        return 'user';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('superuser, status, requires_new_password, login_attempts, login_time', 'numerical', 'integerOnly'=>true),
            array('username, login_ip, address', 'length', 'max'=>45),
            array('password, email, activkey, activation_key', 'length', 'max'=>120),
            array('gender', 'length', 'max'=>1),
            array('salt, validation_key', 'length', 'max'=>255),
            array('reset_token', 'length', 'max'=>250),
            array('image', 'length', 'max'=>450),
            array('create_at, lastvisit_at, create_time, update_time', 'safe'),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('id, username, password, email, gender, activkey, create_at, lastvisit_at, superuser, status, salt, requires_new_password, login_attempts, login_time, login_ip, activation_key, validation_key, create_time, update_time, reset_token, image, address', 'safe', 'on'=>'search'),
               array('image', 'file','types'=>'jpg, gif, png', 'allowEmpty'=>true, 'on'=>'update'),
                    //array('title, image', 'length', 'max'=>255, 'on'=>'insert,update'),
                    );
    }

    /**
     * @return array relational rules.
     */
    public function relations()
    {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
            'userJoinEvents' => array(self::HAS_MANY, 'UserJoinEvent', 'User_user_id'),
            'userRateReviewNgos' => array(self::HAS_MANY, 'UserRateReviewNgo', 'User_user_id'),
            'userUploadVideos' => array(self::HAS_MANY, 'UserUploadVideo', 'User_user_id'),
            'userWriteStories' => array(self::HAS_MANY, 'UserWriteStory', 'User_user_id'),
            'volunteerForms' => array(self::HAS_MANY, 'VolunteerForm', 'User_user_id'),
                        //'profile' => array(self::BELONGS_TO, 'profile', 'id','through'=>'user'),
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'id' => 'ID',
            'username' => 'Username',
            'password' => 'Password',
            'email' => 'Email',
            'gender' => 'Gender',
            'activkey' => 'Activkey',
            'create_at' => 'Create At',
            'lastvisit_at' => 'Lastvisit At',
            'superuser' => 'Superuser',
            'status' => 'Status',
            'salt' => 'Salt',
            'requires_new_password' => 'Requires New Password',
            'login_attempts' => 'Login Attempts',
            'login_time' => 'Login Time',
            'login_ip' => 'Login Ip',
            'activation_key' => 'Activation Key',
            'validation_key' => 'Validation Key',
            'create_time' => 'Create Time',
            'update_time' => 'Update Time',
            'reset_token' => 'Reset Token',
            'image' => 'Image',
            'address' => 'Address',
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search()
    {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.

        $criteria=new CDbCriteria;

        $criteria->compare('id',$this->id);
        $criteria->compare('username',$this->username,true);
        $criteria->compare('password',$this->password,true);
        $criteria->compare('email',$this->email,true);
        $criteria->compare('gender',$this->gender,true);
        $criteria->compare('activkey',$this->activkey,true);
        $criteria->compare('create_at',$this->create_at,true);
        $criteria->compare('lastvisit_at',$this->lastvisit_at,true);
        $criteria->compare('superuser',$this->superuser);
        $criteria->compare('status',$this->status);
        $criteria->compare('salt',$this->salt,true);
        $criteria->compare('requires_new_password',$this->requires_new_password);
        $criteria->compare('login_attempts',$this->login_attempts);
        $criteria->compare('login_time',$this->login_time);
        $criteria->compare('login_ip',$this->login_ip,true);
        $criteria->compare('activation_key',$this->activation_key,true);
        $criteria->compare('validation_key',$this->validation_key,true);
        $criteria->compare('create_time',$this->create_time,true);
        $criteria->compare('update_time',$this->update_time,true);
        $criteria->compare('reset_token',$this->reset_token,true);
        $criteria->compare('image',$this->image,true);
        $criteria->compare('address',$this->address,true);

        return new CActiveDataProvider($this, array(
            'criteria'=>$criteria,
        ));
    }
}

and this is the user join event model

<?php

/**
 * This is the model class for table "user_join_event".
 *
 * The followings are the available columns in table 'user_join_event':
 * @property integer $id
 * @property integer $user_id
 * @property integer $event_id
 * @property string $date_created
 * @property string $date_modified
 *
 * The followings are the available model relations:
 * @property Event $event
 * @property User $user
 */
class UserJoinEvent extends CActiveRecord
{
    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return UserJoinEvent the static model class
     */
    public static function model($className=__CLASS__)
    {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName()
    {
        return 'user_join_event';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('user_id, event_id, date_created, date_modified', 'required'),
            array('user_id, event_id', 'numerical', 'integerOnly'=>true),
            array('date_created, date_modified', 'length', 'max'=>45),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('id, user_id, event_id, date_created, date_modified', 'safe', 'on'=>'search'),
        //http://stackoverflow.com/questions/18434575/to-store-datetime-automatically-using-yii
                    );
    }

    /**
     * @return array relational rules.
     */
    public function relations()
    {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
            'event' => array(self::BELONGS_TO, 'Event', 'event_id'),
            'user' => array(self::BELONGS_TO, 'User', 'user_id'),
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'id' => 'ID',
            'user_id' => 'User',
            'event_id' => 'Event',
            'date_created' => 'Date Created',
            'date_modified' => 'Date Modified',
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search()
    {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.

        $criteria=new CDbCriteria;

        $criteria->compare('id',$this->id);
        $criteria->compare('user_id',$this->user_id);
        $criteria->compare('event_id',$this->event_id);
        $criteria->compare('date_created',$this->date_created,true);
        $criteria->compare('date_modified',$this->date_modified,true);

        return new CActiveDataProvider($this, array(
            'criteria'=>$criteria,
        ));
    }
}

Thankyou.

Salik Asad
  • 291
  • 4
  • 15

2 Answers2

1
    This is a simple solution, not a good pratice but really simple 
    You decode the value you need inside the show loop.. For a fast solution can be useful 

And a allstat.php(in the view file of UserJoinEvent) which is

<div>
    <?php
        foreach($user as $show)
        {
           $model = User::model()->findByAttributes(array('id'=>$show->user_id,));
           if (isset($model)) then {
               echo '<h3>' . $show->user_id .  ' - ' . $model->username . '</h3>';
           } else {
               echo '<h3>' . $show->user_id .  ' - Username not found</h3>';
           }

        ?>
    </div>
ScaisEdge
  • 131,976
  • 10
  • 91
  • 107
  • I have update teh answer .. missign the field user_name. I suppose the user id is id and the user name is user_name, adapt the name to your need. – ScaisEdge Dec 19 '15 at 17:53
  • there is some syntax error with this line echo '

    ' . $show->user_id . ' - ' . $username_>user_name '

    '; cant find out the reason, please update it again, thankyou
    – Salik Asad Dec 19 '15 at 18:12
  • Yes, _ instead of - but remember use the right field name for id and user_name... i have update the answer. – ScaisEdge Dec 19 '15 at 18:29
  • There is an error saying "Trying to get property of non-object " on the echo line.. i have also changed the field name according to my project..!! – Salik Asad Dec 19 '15 at 18:42
  • Check the id for Model User. In the findByAttributes function I use 'id' for match the user_id. but i don't know your name of this field. nor for the user_name.. adapt the name of the field .. please. or otherwise show me your User Model.... – ScaisEdge Dec 19 '15 at 18:51
  • I have update the answer ... using the correct field name – ScaisEdge Dec 20 '15 at 07:00
  • thanks for your response mate, but i have already used the filed names according to my model, it is giving some other error which is not related to the filed name which is " Trying to get property of non-object " on this line of the code "echo '

    ' . $show->user_id . ' - ' . $model->username .'

    ';"
    – Salik Asad Dec 20 '15 at 07:16
  • This mean you don't have User related to the $show->user_id value. don't make sense. Have you value for ser_in UserJoinEvent not related to user?.. (could be)? – ScaisEdge Dec 20 '15 at 07:21
  • I have the following fields in my user_join_event table "id(pk)", "user_id(fk)" and "event_id(fk)", may be you can find a clue from this. i have also updated the user_join_event model code in the question – Salik Asad Dec 20 '15 at 07:26
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/98462/discussion-between-salik-asad-and-scaisedge). – Salik Asad Dec 20 '15 at 07:30
  • This mean the field user_id in table user_join_event must match the field id in table user like in findAttributeByName('id'=>$show->user_id.. in fail the value don't match.... – ScaisEdge Dec 20 '15 at 07:32
  • Just for curiosity, why don't work before? bad user id in user_join_event? – ScaisEdge Dec 20 '15 at 07:35
  • i don't know mate, I guess we just missed the isset condition on the model, and i wanted to ask same question too, and kindly can you explain me this view file briefly what is happening here..!! – Salik Asad Dec 20 '15 at 07:43
  • Is simple in the view you do a loop on the result of the first 4 user_id. For each user_id the User::...findByAttribute() function retrieve the model of the user that match the user_id and by the model get the username. If the model is not set mean no user are related to the user_id in user_join_event,. – ScaisEdge Dec 20 '15 at 12:26
  • Thank you for the explanation. – Salik Asad Dec 20 '15 at 18:25
  • Hi @scaisEdge, can you please have a look at this when you are free, thank you http://stackoverflow.com/questions/34421611/yii-sql-query-for-getting-the-top-users-for-every-month-and-top-users-at-the-en – Salik Asad Dec 22 '15 at 17:46
0

Model

$user=UserJoinEvent::model()->findAll(array(//yeh hum model isi query mein chala raya hain because jab mein ne
                                                    //yeh $rbmodel=userjoinevent::model->findall() se kia tha to yeh mujhay saray results userjoinevent ke show raha 
                                                    //tha, matlab sari user_id of this table show kar raha tha
                'select'=>'CONCAT(user_id," - ", user_name) as name',
                'group'=>'user_id',
                'order'=>'COUNT(*) DESC',
                'limit' =>  5
             ));  

View

<div>
        <?php
            foreach($user as $show)
            {
                echo '<h3>' . $show->name . '</h3>';
            }
        ?>
    </div>
Alaa M. Jaddou
  • 1,180
  • 1
  • 11
  • 30