Yii:如何从db获取多个数据

时间:2015-12-02 19:50:51

标签: php yii

我是一个yiibie。我试图从数据库中获取数据到首页。表名是story,我想从表中获取标题和故事。为此,我在我的视图文件中创建了一个allstory.php文件,并在allstory()中创建了storycontroller的函数。 这是我的控制器的代码。

<?php

class StoryController extends RController
{
    /**
    * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
    * using two-column layout. See 'protected/views/layouts/column2.php'.
    */
    public $layout='//layouts/admin';

    /**
    * @return array action filters
    */
    public function filters()
    {
        return array(
//          'accessControl', // perform access control for CRUD operations
//          'postOnly + delete', // we only allow deletion via POST request
                    'rights',
        );
    }

    /**
    * Specifies the access control rules.
    * This method is used by the 'accessControl' filter.
    * @return array access control rules
    */
    public function accessRules()
    {
        return array(
            array('allow',  // allow all users to perform 'index' and 'view' actions
                'actions'=>array('index','view'),
                'users'=>array('*'),
            ),
            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions'=>array('create','update'),
                'users'=>array('@'),
            ),
            array('allow', // allow admin user to perform 'admin' and 'delete' actions
                'actions'=>array('admin','delete'),
                'users'=>array('admin'),
            ),
            array('deny',  // deny all users
                'users'=>array('*'),
            ),
        );
    }

    /**
    * Displays a particular model.
    * @param integer $id the ID of the model to be displayed
    */
    public function actionView($id)
    {
        $this->render('view',array(
            'model'=>$this->loadModel($id),
        ));
    }
public function actionAllstory() //This has been added to view all the stories on the  stories page
    {
               $this->layout='main';
        $this->render('allstory');
    }

    /**
    * Creates a new model.
    * If creation is successful, the browser will be redirected to the 'view' page.
    */
    public function actionCreate()
    {
        $model=new Story;

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if(isset($_POST['Story']))
        {
            $model->attributes=$_POST['Story'];
            if($model->save())
                $this->redirect(array('view','id'=>$model->id));
        }

        $this->render('create',array(
        'model'=>$model,
        ));
    }

    /**
    * Updates a particular model.
    * If update is successful, the browser will be redirected to the 'view' page.
    * @param integer $id the ID of the model to be updated
    */
    public function actionUpdate($id)
    {
        $model=$this->loadModel($id);

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

        if(isset($_POST['Story']))
        {
            $model->attributes=$_POST['Story'];
            if($model->save())
                $this->redirect(array('view','id'=>$model->id));
        }

        $this->render('update',array(
            'model'=>$model,
        ));
    }

    /**
    * Deletes a particular model.
    * If deletion is successful, the browser will be redirected to the 'admin' page.
    * @param integer $id the ID of the model to be deleted
    */
    public function actionDelete($id)
    {
        if(Yii::app()->request->isPostRequest)
        {
            // we only allow deletion via POST request
            $this->loadModel($id)->delete();

            // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
            if(!isset($_GET['ajax']))
                $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
        }
        else
            throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
    }

    /**
    * Lists all models.
    */
    public function actionIndex()
    {
        $dataProvider=new CActiveDataProvider('Story');
        $this->render('index',array(
            'dataProvider'=>$dataProvider,
        ));
    }

    /**
    * Manages all models.
    */
    public function actionAdmin()
    {
        $model=new Story('search');
        $model->unsetAttributes();  // clear any default values
        if(isset($_GET['Story']))
            $model->attributes=$_GET['Story'];

        $this->render('admin',array(
            'model'=>$model,
        ));
    }

    /**
    * Returns the data model based on the primary key given in the GET variable.
    * If the data model is not found, an HTTP exception will be raised.
    * @param integer $id the ID of the model to be loaded
    * @return Story the loaded model
    * @throws CHttpException
    */
    public function loadModel($id)
    {
        $model=Story::model()->findByPk($id);
        if($model===null)
            throw new CHttpException(404,'The requested page does not exist.');
        return $model;
    }

    /**
    * Performs the AJAX validation.
    * @param Story $model the model to be validated
    */
    protected function performAjaxValidation($model)
    {
        if(isset($_POST['ajax']) && $_POST['ajax']==='story-form')
        {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }
}

这是我的allstory.php视图文件

 <div class="content">
                                     <div class="banner">
                                         <img src="<?php echo Yii::app()->request->baseurl;?>/img/story-banner.jpg" class="img-responsive">
                                         </div><!--banner ending here--><br>
                                         <div class="story-content">


                                              <div class="row">
                                                 <div class="col-md-8 col-md-offset-2 vol-stories">
                                                     <div class="media">
                                        <div class="media-left">
                                            <a href="user-profile.php">
                                                <?php $modelnew=$model->story;
                                                foreach($modelnew as $test)
                                                {
                                                ?>
                                              <img class="media-object" src="<?php echo Yii::app()->request->baseurl;?>/img/media.jpg">
                                          </a>
                                       </div>
                                        <div class="media-body"><strong><?php echo $test->user->username;?></strong> <!--username will come here-->

                                    <h4 class="media-heading"><strong><br><br><?php echo $test->title?></strong></h4><!--title will come here-->
                                       <p><?php echo $test->story?></p><!--story will come here-->
                                        <?php
                                                }
                                                ?>      
                                        </div>


                                              </div><!--Media ending here--> 
                                                 </div>
                                             </div><!--row ending here--><br>

                                             <hr>
                                             <div class="write-story">
                                                 <div class="row">
                                                     <div class="col-md-6 col-md-offset-3"><br>
                                                         <form>
                                                             <strong>Title:</strong><textarea class="form-control" rows="1"></textarea>
                                                         </form>
                                                     </div>
                                                 </div><!--row ending here-->
                                                  <div class="row">
                                                     <div class="col-md-6 col-md-offset-3"><br>
                                                         <form>
                                                             <strong>Story:</strong><textarea class="form-control" rows="3"></textarea>
                                                         </form>
                                                     </div>
                                                 </div><!--row ending here-->
                                                 <div class="row">
                                                  <div class="col-md-6 col-md-offset-3"><br>
                                                 <button class="btn btn-primary">Share</button>

                                                 </div>
                                                     </div><br>
                                                 </div><!--write-story ending here-->



</div><!--content ending here-->


                           </div><!--container ending here-->

这是故事模型

<?php

/**
 * This is the model class for table "story".
 *
 * The followings are the available columns in table 'story':
 * @property integer $id
 * @property string $title
 * @property string $story
 * @property integer $user_id
 *
 * The followings are the available model relations:
 * @property User $user
 */
class Story extends CActiveRecord
{
    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return Story 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 'story';
    }

    /**
     * @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('title, story, user_id', 'required'),
            array('user_id', 'numerical', 'integerOnly'=>true),
            array('title', 'length', 'max'=>100),
            array('story', 'length', 'max'=>1000),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('id, title, story, user_id', 'safe', 'on'=>'search'),
        );
    }

    /**
     * @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(
            'user' => array(self::BELONGS_TO, 'User', 'user_id'),
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'id' => 'ID',
            'title' => 'Title',
            'story' => 'Story',
            'user_id' => 'User',
        );
    }

    /**
     * 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('title',$this->title,true);
        $criteria->compare('story',$this->story,true);
        $criteria->compare('user_id',$this->user_id);

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

这是个人资料的模型

<?php

/**
 * This is the model class for table "profiles".
 *
 * The followings are the available columns in table 'profiles':
 * @property integer $user_id
 * @property string $lastname
 * @property string $firstname
 * @property string $picture
 *
 * The followings are the available model relations:
 * @property User $user
 */
class Profiles extends CActiveRecord
{
    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return Profiles 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 'profiles';
    }

    /**
     * @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('lastname, firstname', 'length', 'max'=>50),
            array('picture', 'length', 'max'=>500),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('user_id, lastname, firstname, picture', 'safe', 'on'=>'search'),
        );
    }

    /**
     * @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(
            'user' => array(self::BELONGS_TO, 'User', 'user_id'),
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'user_id' => 'User',
            'lastname' => 'Lastname',
            'firstname' => 'Firstname',
            'picture' => 'Picture',
        );
    }

    /**
     * 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('user_id',$this->user_id);
        $criteria->compare('lastname',$this->lastname,true);
        $criteria->compare('firstname',$this->firstname,true);
        $criteria->compare('picture',$this->picture,true);

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

这是用户的模型

<?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,
        ));
    }
}

我无法得到任何结果,因为我不知道我这样做是对还是错。当我使用此代码时,它也会给我一个Undefined variable: model

的错误

1 个答案:

答案 0 :(得分:1)

首先你有

 class StoryController extends RController

为什么要扩展RController而不仅仅是Controller?

然后对于控制器,如果你想要一个id的故事,你需要像这样的行动

public function actionSingleStory($id) //This has been added to view a single story 
{
    $model=$this->loadModel($id);

    $this->layout='main';
    $this->render('singlestory', array('model'=>$model));
}

和这样的简化视图(singlestory.php)(我假设你有字段$ model-&gt; story_title amd $ model-&gt; story_text

<div class="content">
    <div class="banner">
         <img src="<?php echo Yii::app()->request->baseurl;?>/img/story-banner.jpg" class="img-responsive">
    </div><!--banner ending here--><br>
    <div class="story-content">


        <div class="row">
            <div class="col-md-8 col-md-offset-2 vol-stories">
                 <div class="media">
                    <div class="media-left">
                        <a href="user-profile.php">
                            <img class="media-object" src="<?php echo Yii::app()->request->baseurl;?>/img/media.jpg">
                        </a>
                    </div>
                    <div class="media-body"><strong><?php echo $test->user->username;?></strong> <!--username will come here-->
                        <h4 class="media-heading"><strong><br><br><?php echo $model->story_title?></strong></h4><!--title will come here-->
                        <p><?php echo $model->story_text?></p><!--story will come here-->
                     </div>
                </div><!--Media ending here--> 
            </div>
        </div><!--row ending here-->
    </div><!--content ending here-->
</div><!--container ending here-->

如果你想要所有的故事

public function actionAllstory() //This has been added to view all the stories on the  stories page
{

     $allmodels =  Story::model()->findAll();
     $this->layout='main';
     $this->render('allstory', array('allmodels' => $allmodels));
}

在视图中(简化的allstory.php)

<div class="content">
    <div class="banner">
         <img src="<?php echo Yii::app()->request->baseurl;?>/img/story-banner.jpg" class="img-responsive">
    </div><!--banner ending here--><br>
    <div class="story-content">


        <div class="row">
            <div class="col-md-8 col-md-offset-2 vol-stories">
                 <div class="media">
                    <div class="media-left">
                        <a href="user-profile.php">
                            <img class="media-object" src="<?php echo Yii::app()->request->baseurl;?>/img/media.jpg">
                        </a>
                    </div>
                    <?php 
                        foreach($allmodels as $model){
                            echo "<h4 class='media-heading'><strong>" . $model->story_title ."</strong></h4>" ; //<!--title will come here-->
                            echo "<p>" .  $model->story_text . "</p>" ; // <!--story will come here-->
                        }
                    ?>
                </div><!--Media ending here--> 
            </div>
        </div><!--row ending here-->
    </div><!--content ending here-->
</div><!--container ending here-->