使用GridView筛选器字段在相关模型中搜索 [英] Search in Related Model using GridView Filter Field
问题描述
问题: 假设我有两个桌子,
Question: Let's Say i have two tables,
Table1 Table2
-authorId -username
到目前为止,我在搜索模型上的sql查询看起来像这样,
As of now my sql query on search model looks like this,
->andFilterWhere(['"Table1"."authorId"' => $this->authorName]);
它仅有助于使用authorID搜索和过滤.
It only helps to search and filter using the authorID.
预期结果 我想基于作者名而不是authorId进行搜索.
Expected Result I would like to search based on the authorname instead of authorId.
我在将数据反映到视图中时也遇到了类似的困难,但是我可以通过在基本模型中使用以下getter函数对其进行修复.
I faced similar difficulty in reflecting data in view but i was able to fix it with following getter function in base model.
public function getAuthorName() {
return $this->author->username;
}
预先感谢,
推荐答案
首先,向您的搜索模型添加自定义属性
First, add a custom attribute to your search model
public $username
在模型内定义与您的author
表的关系
define a relation to your author
table inside the model
public function getAuthor() {
return $this->hasOne(Author::className(),['id'=>'authorId']);
}
gridview
中的
用
`author.username`
并使用以下内容进行比较
and use the following to compare
$query->andFilterWhere(['like', '{{%Table2}}.username',$this->username]);
是的,请确保您在搜索功能开始时将您的searchmodel查询与author
表一起加入
and yes make sure you join you searchmodel query with the author
table in the start of search function
->joinWith('author')
这篇关于使用GridView筛选器字段在相关模型中搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!