zelenin писал(а):
я вам уже модель сверху скинул именно с вашим вариантом доп. поля.
Только что воспроизвел ситуацию на чистом basic проекте. Попробуйте у себя этот код. Если и у вас не выдаст ошибку... В общем скидываю все, что касается данной проблемы:
миграция для модели:
Код: Выделить всё
class m150303_171520_create_table_Users extends Migration
{
public function up()
{
$this->createTable('user',['id' => Schema::TYPE_PK,
'name VARCHAR(45) NULL',
'date_of_birth DATE NULL']);
$this->insert('user', ['id' =>null, 'name'=>'Alex', 'date_of_birth'=>'1980-01-01']);
$this->insert('user', ['id' =>null, 'name'=>'Max', 'date_of_birth'=>'1990-01-01']);
$this->insert('user', ['id' =>null, 'name'=>'Vera', 'date_of_birth'=>'1995-01-01']);
}
public function down()
{
echo "m150303_171520_create_table_Users cannot be reverted.\n";
return false;
}
}
Модель:
Код: Выделить всё
namespace app\models;
use Yii;
/**
* This is the model class for table "user".
*
* @property integer $id
* @property string $name
* @property string $date_of_birth
*/
class User extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'user';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['date_of_birth'], 'safe'],
[['name'], 'string', 'max' => 45]
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'name' => 'Name',
'date_of_birth' => 'Date Of Birth',
];
}
}
Модель поиска:
Код: Выделить всё
namespace app\models;
use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\User;
/**
* UserSearch represents the model behind the search form about `app\models\User`.
*/
class UserSearch extends User
{
public $age_from;
/**
* @inheritdoc
*/
public function rules()
{
return [
[['id'], 'integer'],
[['name', 'date_of_birth'], 'safe'],
['age_from', 'number']
];
}
/**
* @inheritdoc
*/
public function scenarios()
{
// bypass scenarios() implementation in the parent class
return Model::scenarios();
}
/**
* Creates data provider instance with search query applied
*
* @param array $params
*
* @return ActiveDataProvider
*/
public function search($params)
{
$query = User::find();
$query->select(['*', new \yii\db\Expression('(YEAR(current_date())-YEAR(date_of_birth)) as age')]);
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$this->load($params);
if($this->age_from)
$query->andHaving('age >= :age_from', [':age_from' => $this->age_from]);
if (!$this->validate()) {
// uncomment the following line if you do not want to any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
$query->andFilterWhere([
'id' => $this->id,
'date_of_birth' => $this->date_of_birth,
]);
$query->andFilterWhere(['like', 'name', $this->name]);
return $dataProvider;
}
}
Экшн контроллера, который отвечает за поиск:
Код: Выделить всё
public function actionIndex()
{
$searchModel = new UserSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams)->getModels();
return $this->render('index', [
'dataProvider' => $dataProvider,
'model' => $searchModel
]);
}
Кусок вьюхи, в котором есть форма и выводится найденная информация (в данном случае имена)
Код: Выделить всё
<?php
$form = ActiveForm::begin([
'method' => 'get',
'action' => \yii\helpers\Url::to('/user/index'),
'id' => 'user-search',
'enableClientValidation' => false,
'options' => ['class' => 'form-inline main-filter'],
'fieldConfig' => [
'template' => '{label}{input}{error}',
],
]);?>
<?= $form->field($model, 'name'); ?>
<br />
<?= $form->field($model, 'age_from')->input('text',['onkeyup'=>'this.value=parseInt(this.value) | 0']) ?>
<button type="submit" class="btn btn-primary">Поиск</button>
<?php ActiveForm::end(); ?>
<?php
foreach($dataProvider as $value)
{
echo $value->name, ' ';
}
?>