2

我刚刚在我的应用程序中使用了 Yii2。我想在索引视图中创建搜索过滤器表单,其属性来自不同模型的过滤器活动和非活动。

我有两个表“员工”和“合同”..

tbl_employee
id_employee
name
dob
address
等。

tbl_contract
id
日期
状态

在索引中我使用了这段代码

<?php echo $this->render('_search', ['model' => $searchModel]); ?>

我想在索引视图中过滤有有效合同的员工和没有有效合同的员工

这个_search.php

<?php $form = ActiveForm::begin([
    'action' => ['index'],
    'method' => 'get',
]); ?>

<?= $form->field($model, 'id_number')->textInput(['maxlength'=>6,'style'=>'width:225px']) ?>

<?= $form->field($model, 'name') ->textInput(['maxlength'=>30,'style'=>'width:225px']) ?>              

<?php $data = ['Active'=> 'Active', 'Inactive'=>'Inactive'];

echo '<label class="control-label">Status</label>';
echo Select2::widget([
'name' => 'Status_Contract',
'data' => $data,
'options' => [
    'placeholder' => 'Select Status Contract ...',
    ],
]);
?>

<div class="form-group">
    <?= Html::submitButton(Yii::t('app', 'Search'), ['class' => 'btn btn-success']) ?>
    <?= Html::a('Reset', ['/employee/index'], ['class'=>'btn btn-default']) ?>
</div>
<?php ActiveForm::end(); ?>

模型\雇员 EmpSearch.php

$query = Employee::find()->joinWith('p_contract');

$dataProvider = new ActiveDataProvider([
        'query' => $query,

if (!($this->load($params) && $this->validate())) {
        return $dataProvider;
    }
    ]);
$query->andFilterWhere([
'id' => $this->id,
]);

$query->andFilterWhere(['like', 'name', $this->name]);

我的网络中的这个搜索表单

在此处输入图像描述

位于合同模型中的属性“状态”。像这样的关系。

public function getP_contract()
{
    return $this->hasOne(Contract::className(), ['id_emp' => 'id_employee', 'id' => 'id_contract']);
}

那么,如何根据合同“活动”或“非活动”创建搜索表单。请帮我解决这个问题。

4

1 回答 1

1

似乎您已经在模型中建立了获取状态的适当关系,因此您应该为新的字段搜索状态添加一个属性

/* your related attribute */
public $status;

并且您已经为 p_contract 加入了一个连接,因此您应该添加过滤器 where for status

 // filter by status
   $query->joinWith(['p_contract' => function ($q) {
       $q->where('contratct_table_name.status LIKE "%' . $this->status. '%"');
}]);

您可以查看本教程以获取更多信息 http://www.yiiframework.com/wiki/621/filter-sort-by-calculated-related-fields-in-gridview-yii-2-0/ (参见场景2)

于 2017-07-05T05:47:26.170 回答