Search in Related Model using GridView Filter Field

你说的曾经没有我的故事 提交于 2019-12-13 02:48:43

问题


Question: Let's Say i have two tables,

Table1            Table2
-authorId         -username

As of now my sql query on search model looks like this,

->andFilterWhere(['"Table1"."authorId"' => $this->authorName]);

It only helps to search and filter using the authorID.

Expected Result I would like to search based on the authorname instead of authorId.


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;
    }

Thanks in Advance,


回答1:


First, add a custom attribute to your search model

public $username

define a relation to your author table inside the model

public function getAuthor() {
        return $this->hasOne(Author::className(),['id'=>'authorId']);
    }

in your gridview replace the authorId column with

`author.username`

and use the following to compare

$query->andFilterWhere(['like', '{{%Table2}}.username',$this->username]);

and yes make sure you join you searchmodel query with the author table in the start of search function

->joinWith('author')



回答2:


Assuming authorId is a FK to table2, and you have previoulsy joined table2 to table1, you can do the following:

->andFilterWhere(['table2.username' => $this->authorName]);


来源:https://stackoverflow.com/questions/48418082/search-in-related-model-using-gridview-filter-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!