我有两个数据库表“用户”和“角色”。我使用 Yii 框架 2.0 Gii 来创建带有 User 模型和 UserSearch 模型的 CRUD。默认情况下,Gii 使用 GridView::widget 作为“用户”模型的索引页面。
在 UserSearch 模型中的 search($params) 方法中,我使用以下代码将上述表格连接在一起
$query = User::find()->with('role');
查询一切正常。
默认情况下,Gii 不包含 views/user/index.php 页面内 GridView::widget 中连接表 'role' 的数据。通过上面的连接查询,我可以从两个表中检索数据。在 views/user/index.php 页面中,我在 GridView::widget 中注入(inject)了以下代码,以便它还包含连接表(角色)中的数据和列名。
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'userid',
'username',
'role.role_name',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
GridView::widget 中包含的角色数据'role_name 一切正常。但问题是没有role_name 的搜索框。 GridView::widget 仅为用户属性创建搜索框。有什么方法可以为联接表“role”的属性添加搜索框,因为我还想搜索“role_name”以及用户模型的其他属性。
最佳答案
试试这个方法:
在您的 UserSearch 模型中添加
UserSearch extends ...
{
public $roleFilterInputName; //the name of the filter search input
//important
function rules()
{
//add roleFilterInputName as safe
return [
[['xxx', 'roleFilterInputName'], 'safe'], //!!!!
];
}
}
在你的网格中:
'columns':
[
//...
[
'attribute' => 'roleFilterInputName',
'value' => 'role.role_name'
],
//...
]
在 UserSearch::search() 中
$query->andFilterWhere(['like', 'role.role_name', $this->roleFilterInputName])
但我猜你必须使用“joinWith”而不是“with”。
关于php - Yii Framework 2.0 GridView 和来自连接表的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26041543/