Hi, i’m trying to create a specific search functionality using the search model with Yii2, but i’m not sure how could i achieve what i want.
I want to let the user add as many fields as he wants (related to the same model attribute, same concept as tabular input) and perfom an AND query or an OR query based on user choice. I know this doesn’t make much sense at first, don’t know how to properly explain it so i’ll try to elaborate as much as i can.
Let’s say I have a table called persons, in this table there’s a column named per_gender, per_name and per_lastname. The user may want to know all the persons in this table that are female and who’s last name is “Aniston” OR all the persons that are male and who’s last name is “Smith”. The raw MySQL query that gives te desired results is as follows:
SELECT *
FROM persons
WHERE per_gender = "F" AND per_lastname = "Aniston" OR per_gender = "M" AND per_lastname = "Smith"
So i need to make this query in my search model. It could be represented like this (just a theory):
class PersonsSearch extends Persons{
...
public function search($params){
$query = Persons::find();
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
...
...
$query->andFilterWhere(['per_gender' => $this->per_gender1])->andFilterWhere(['per_lastname' => $this->per_lastname1]);
$query->orFilterWhere(['per_gender' => $this->per_gender2])->andFilterWhere(['per_lastname' => $this->per_lastname2]);
}
...
return $dataProvider;
}
The query above is just an example, i tried to make it as simple as possible. The user can enter as many conditions as he/she wants and "mold" the query accordingly as well.
How can this be achieved? the only thing i could come up with was tabular input but i don’t know if it’s the right way to do it or how can i implement it for search model.
Any help would be highly appreciated, i know this could be confusing so let me know if any additional info is needed.