我在控制器部门的班级上有这个
大家好
所以我想通过yii实现一些目标
我有一个Departments表和一个Student表。在学生视图内部,我想显示部门名称和过滤器。 虽然我可以显示每个学生的部门名称,但是不会显示部门名称过滤器。
下面是带注释的代码:
/*Begining of Students model*/
class Students extends \yii\db\ActiveRecord
/ *这是我对学生表进行引用的地方* /
public function getDepartments()
{
return $this->hasMany(Departments::className(), ['department_id' => 'ID']);
}
---学生人数模型
---学生视图的开始
/*Inside my view folder i have the Students folder where i have an index.php file where everything is listed in Gridview. */
View / Students / index.php
<?php
use yii\helpers\Html;
use yii\grid\GridView;
use yii\helpers\ArrayHelper;
use app\models\States;
use kartik\export\ExportMenu;
/* @var $this yii\web\View */
/* @var $searchModel app\models\AgentsSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */
$this->title = 'Agents';
$this->params['breadcrumbs'][] = $this->title;
$gridColumns = [
['class' => 'yii\grid\SerialColumn'],
'created_at',
'name',
departments.name',
'status',
['class' => 'yii\grid\ActionColumn'],
];
// Renders a export dropdown menu
echo ExportMenu::widget([
'dataProvider' => $dataProvider,
'columns' => $gridColumns
]);
?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'tableOptions' =>['class'=>'table table-bordered'],
'filterModel' => $searchModel,
'columns' => $gridColumns
]); ?>
</div>
/*End of Students view*/
/*Begining of Students search.*/
/*models/StudentsSearch.php*/
我了解到,StudentsSearch.php文件中下面的代码负责显示每个字段的过滤器。
public function rules()
{
return [
[['phone'], 'integer'],
//my understanding is that this is what controls the filter form, only fields listed here have filters
[['phone','name' 'email', 'address','city','departments.name'], 'safe'],
];
}
/*End of Students search.*/
我能够为所有其他内容显示过滤器,但是如何为部门名称显示过滤器?
答案 0 :(得分:0)
StudentsSearch
中,例如$departmentName
[['departmentName'], 'safe']
$query->andFilterWhere(['like', 'department.name', $this->departmentName])
在计算字段上进行排序的工作原理类似,请阅读:https://www.yiiframework.com/wiki/621/filter-sort-by-calculatedrelated-fields-in-gridview-yii-2-0
$dataProvider->setSort([
'attributes' => [
'id',
'departmentName' => [
'asc' => ['department.name' => SORT_ASC],
'desc' => ['department.name' => SORT_DESC],
'label' => 'Department',
'default' => SORT_ASC
],
]
]);
答案 1 :(得分:0)
通过将“部门”表添加到规则中来对其进行引用。
public function rules()
{
return [
//this controls the filter section, only fields listed here will have filter
[['Department'], 'safe'],
];
}
然后在这种情况下,在“学生”视图中的index.php中,我添加属性“部门”,并使用gridColumns中的department.name引用部门名称
$gridColumns = [
['class' => 'yii\grid\SerialColumn'],
'name',
'email:email',
'address',
[
'attribute' => 'departments',
'label' => Department Name',
'value' => 'department.name'
],
'status',
['class' => 'yii\grid\ActionColumn'],
];
?>
添加department.name属性。
公共函数attributeLabels() { 'Department.name'=>'部门名称' }