B
B
bdFregat2018-09-18 10:38:46
Yii
bdFregat, 2018-09-18 10:38:46

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

What am I doing wrong?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
B
bdFregat, 2018-09-18
@bdFregat

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.

D
Dmitry, 2018-09-18
@slo_nik

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 question

Ask a Question

731 491 924 answers to any question