Answer the question
In order to leave comments, you need to log in
How to select using DISTINCT in yii2(AR)?
Good evening.
Tell me how to make a selection in Yii2 with DISTINCT so that I can get the value of not only those fields that are listed for distinct, but also any others?
For example, I have the following query:
$model = User::find()
->select( ['sender_id', 'recipient_id'] )
->distinct()
->all()
Answer the question
In order to leave comments, you need to log in
with this choice, I get only unique rows in the database with the sender_id and recipient_id fields, but there are other fields there.
$expression = new \yii\db\Expression('id IN (SELECT MAX(id) FROM messages WHERE `sender_id` = :user_id OR `recipient_id` = :user_id, GROUP BY IF (`sender_id` = :user_id, `recipient_id`, `sender_id`))',[':user_id' => 3]);
$models = Messages::find()->where($expression);
with this choice, I get only unique rows in the database with the sender_id and recipient_id fields, but there are other fields there. How can I get them in such a way that they do not fall under DISTINCT?
SELECT `sender_id`, `recipient_id`
FROM `table`
GROUP BY (`sender_id`, `recipient_id`)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question