Answer the question
In order to leave comments, you need to log in
How to filter by records in Yii2 that are not in the related table?
There is a customer table and a transaction table with a customer ID field.
I need to get "bad" customers - those who have never bought in a certain period of time. That is, you need to find clients for which there are no transactions that satisfy a certain condition.
Tried like this
$sub = Transaction::find()
->select('client_id')
->where(['>', 'amount', 0])
->andWhere(['brand_id' => $brand])
->andWhere(['between', 'created_at', $start_date, $end_date])
//$sub->count() - Находит 2882 транзакции, пользователей никак не меньше
$result = Client::find()
->where(['brand_id' => $brand])
->andWhere(['not exists', $sub]) // Без этой строчки - 3794, это все пользователи
->indexBy('id')
->asArray()
->count();
// Получаем 0, хотя должно быть не меньше 3794 - 2882
Answer the question
In order to leave comments, you need to log in
I close the question, the problem turned out to be that ActiveRecord returns an id with a string type, there is an opinion that this is due to the unsigned int data type. If id come to int, then everything works with a bang.
Good morning.
Perhaps you need to change the line
To
ps What does your $sub get into? As I understand it, there should be an array of id of customers who did not buy anything?
ps Request too would not hurt to change.
$sub = Transaction::find()
->where(['>', 'amount', 0])
->andWhere(['brand_id' => $brand])
->andWhere(['between', 'created_at', $start_date, $end_date])
->column();
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question