Getting a particular row from database in yii

2019-08-24 18:14发布

I am working on a job site.And using Yii.I have gridview which list all the jobs posted by user,but I just want to show the jobs which are posted by a particular user.like if the user is logged in as admin then it should show only jobs posted by admin.I have tried the following things but not working.

 In Controller.


//codes


 public function actionViewJob() {

       $user_id = Yii::app()->session['user_id'];

        /* For User Authentication */
        if (Yii::app()->user->getId() === null)
            $this->redirect(array('site/login'));
        /* For User Authentication */

        $model = ViewJob::model()->find(array(
            'select' => array('*'), "condition" => "user_id= $user_id",
        ));

        $params = array('model' => $model,
        );

        $this->render('viewjob', $params);
    }

 function as search() in model ViewJob.


    public function search()
    {

     $criteria=new CDbCriteria;

     $criteria->compare('key_skills','Admin',true);
     return new CActiveDataProvider('viewjob', array(
       // 'criteria'=>$criteria,
        'sort'=>array(
            'defaultOrder'=>'key_skills ASC',
        ),
    ));


    }

What am I doing wrong here.?.Its still listing the whole data.

标签: php yii
2条回答
混吃等死
2楼-- · 2019-08-24 19:03

Try like

 $model=ViewJob::model()->findByAttributes(array('user_id'=>Yii::app()->user->id));
查看更多
Lonely孤独者°
3楼-- · 2019-08-24 19:03

Try this

 $model = ViewJob::model()->findAll("user_id=$user_id");

 /*
 1. find() can fetch first matched row, where as findAll() fetches all matched rows in the db table
 2. "user_id=$user_id" is equals to WHERE user_id=$user_id
 */

Code improvements(Yii way)

  1. Register user sessions as bellow

    Yii::app()->user->setState('user_id',$value_variable); //Set the session
    Yii::app()->user->getState('user_id'); //Get the session
    
  2. You can use accessRules() for bellow code

     if (Yii::app()->user->getId() === null)
        $this->redirect(array('site/login'));
    

    Like

    public function accessRules()
    {
        return array(            
           array('allow',
            'actions' => array('viewJob'),
            'users' => array('@'),
            ----
            ---
    
查看更多
登录 后发表回答