Добавление где близко на Gii генерируется CRUD

Я новичок в Yii, и я использовал GII для создания таблицы CURD. Все работает нормально, но я только хочу извлечь определенную запись из базы данных, поставив условие where (например, "где пол клиента - мужчина"). Я не могу найти, где данные выбираются из базы данных в сгенерированном коде Gii и где мне нужно вставить предложение WHERE в код.

Как вы знаете, Gii генерирует модель, контроллер и файл представления. Файл модели, как показано ниже. Мой взгляд использовал CGridView для генерации таблицы CRUD.

    public static function model($className = __CLASS__) {
    return parent::model($className);
}

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

/**
 * @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('client_id', 'required'),
        array('client_id', 'length', 'max' => 15),
        array('surname, forename', 'length', 'max' => 20),
        array('title', 'length', 'max' => 6),
        array('status', 'length', 'max' => 8),
        array('dob', 'safe'),
        // The following rule is used by search().
        // Please remove those attributes that should not be searched.
        array('client_id, surname, forename, title, status, dob', '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(
    );
}

/**
 * @return array customized attribute labels (name=>label)
 */
public function attributeLabels() {
    return array(
        'client_id' => 'Client ID',
        'surname' => 'Surname',
        'forename' => 'Forename',
        'title' => 'Title',
        'status' => 'Status',
        'dob' => 'Date of birth (yyyy-mm-dd)',
        'actions' => 'Actions',
    );
}

/**
 * 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('client_id', $this->client_id, true);
    $criteria->compare('surname', $this->surname, true);
    $criteria->compare('forename', $this->forename, true);
    $criteria->compare('title', $this->title, true);
    $criteria->compare('status', $this->status, true);
    $criteria->compare('dob', $this->dob, true);

    return new CActiveDataProvider($this, array(
                'criteria' => $criteria,
                'sort' => array(
                    'defaultOrder' => 'dob DESC',
                ),
            ));
}

1 ответ

Решение

У вас есть два способа выполнить запрос, один из которых с помощью Query Builder ( учебное пособие здесь), например так:

$clientLocalArray = Yii::app()->db->createCommand()
->select()
->from("test_prefixtbl_client_local")
->where("gender = :gender", array(":gender"=>$gender))
->queryAll();

Или вы можете использовать саму Active Record ( учебник здесь) следующим образом:

$clientLocalArrayObjects = ClientLocal::model()->findAllByAttributes(array(
"gender" => $gender
));

Любые сомнения, просто спросите!:)

Другие вопросы по тегам