M
M
michaelromanov902016-10-23 01:21:23
MySQL
michaelromanov90, 2016-10-23 01:21:23

How to correctly select rows from the database by the id collection in Yii2?

Good afternoon!
1) What is the most correct way in Yii2 (QB) to extract all rows by id from the database. At the same time, I have a list of id (s), it is stored in an array, like

$arr = [
     1, 4, 5
];

2) In this case, if there are repetitions in the array, it is necessary to display only the 1st record. (ps in the application, I can not clean this array from repetitions).. The
question is how to do this in the most correct way?
Thank you!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry, 2016-10-23
@michaelromanov90

Goodnight.
You can clean up the array from duplicate data array_unique
Well, in yii2 itself, create a query to fetch data from the database, taking into account the values ​​of your array.
Something like this request

// возвращает покупателей с идентификаторами 100, 101, 123 и 124
// SELECT * FROM `customer` WHERE `id` IN (100, 101, 123, 124)
$customers = Customer::findAll([100, 101, 123, 124]); // передайте сюда свой очищенный от повторений массив

More details here and here
In yii\db\Query there is a $distinct() method and $distinct property, with which you can solve this problem without resorting to array_unique

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question