Reputation: 103
so i have a model that has relations and i've modified the search function to permit querying the relational data but i don't want it to return the entries which have null values inside them. here's my search function:
public function search($params)
{
$query = Services::find();
$query->joinWith(['location', 'client', 'operator']);
$dataProvider = new ActiveDataProvider([
'query' => $query,
'sort'=> ['defaultOrder' => ['date'=>SORT_ASC]]
]);
...
$query->andFilterWhere([
'id' => $this->id,
'tip' => $this->tip,
'status' => $this->status,
]);
if ( ! is_null($this->date) && strpos($this->date, ' - ') !== false ) {
$datelist = explode(' - ', $this->date);
// var_dump($datelist);
// die($datelist);
$start_date = \DateTime::createFromFormat('m-d-Y H:i:s', $datelist[0].' 00:00:00');
$end_date = \DateTime::createFromFormat('m-d-Y H:i:s', $datelist[1].' 23:59:59');
$query->andFilterWhere(['between', 'date', $start_date->format('Y-m-d H:i:s'),$end_date->format('Y-m-d H:i:s')]);
}
$query->andFilterWhere(['like', 'location.address', $this->location]);
$query->andFilterWhere(['like', 'client.name', $this->client]);
$query->andFilterWhere(['like', 'personal.nume', $this->operator_id]);
$query->andFilterWhere(['NOT', [$this->client=>null]]);
$query->andFilterWhere(['NOT', [$this->location=>null]]);
$query->andFilterWhere(['NOT', ['location_id' => null]]);
$query->andFilterWhere(['NOT', ['client_id' => null]]);
return $dataProvider;
}
Notice the last 4 query rows. I think that should omit the rows that have null values in those specific attributes
This is the query generated, it does not include any NOT conditions and i don't get why.
SELECT `services`.* FROM `services` LEFT JOIN `location` ON `services`.`location_id` = `location`.`id` LEFT JOIN `client` ON `services`.`client_id` = `client`.`id` LEFT JOIN `personal` ON `services`.`operator_id` = `personal`.`id` WHERE `date` BETWEEN '2015-01-01 00:00:00' AND '2015-01-22 23:59:59' ORDER BY `client`.`name` DESC LIMIT 20
If someone manages to do this before, please show how :D
Thank you in advance
Upvotes: 0
Views: 1187
Reputation: 81
Instead of using andFilterWhere use andWhere. andFilterWhere ignores the empty operands and thus your null values will not be added to the query.
Replace
$query->andFilterWhere(['NOT', [$this->client=>null]]);
$query->andFilterWhere(['NOT', [$this->location=>null]]);
$query->andFilterWhere(['NOT', ['location_id' => null]]);
$query->andFilterWhere(['NOT', ['client_id' => null]]);
With
$query->andWhere(['NOT',['location_id' => null]])
$query->andWhere(['NOT', ['client_id' => null]]);
Upvotes: 2