M
M
Maxim2018-10-11 02:46:07
Yii
Maxim, 2018-10-11 02:46:07

Yii2 how to remove duplicate records in $dataProvider when joinWith()?

Hello everyone!) I just can’t deal with the data in the dataProvider. Perhaps this applies not only to him, but also to requests.
Essence such... I use model ProfileSearch in which I do joinWith of other tables with necessary data (city, region....).

$query = Profile::find();
        $query = $this->getTabs($query);

        $query->joinWith(['user', 'city', 'certifications', 'appointments.event'])
            ->leftJoin('auth_assignment','auth_assignment.user_id = profile.user_id');

They also sort and filter data.
// grid filtering conditions
        $query->andFilterWhere([
            'id' => $this->id,
            'user_id' => $this->user_id,
            'date_birthday' => $this->date_birthday,
            'city.id' => $this->city_id,
            'gender' => $this->gender,
            'category_id' => $this->category_id,
            'comitet_id' => $this->comitet_id,
            'user.status' => $this->status,
            'auth_assignment.item_name' => $this->type,
            'city.id_district' => $this->district_id,
            'city.id_region' => $this->region_id,
        ]);

I display all this using the ListView widget using dataProvider. After joinWith, the amount of data has increased. For example, there are 100 users in the system, and $dataProvider->totalCount shows 150. Well, this is understandable. After all, they made leftJoin of other data. However, another problem arose. When paginating pages, duplicate users appear.
5bbe8ec3e6ed1961393094.png
Question:
1. How can I remove duplicate entries?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
E
Evgeny Bukharev, 2018-10-11
@myks92

To avoid duplication, group by profile IDs
$query->groupBy('id');

A
Andrey K, 2018-10-11
@kuftachev

When I was struggling with this problem, I decided to see how the professionals do it... I looked at the code of the site yiiframework.com, the news section or something similar, there are many-to-many tags for news... As a result... NOTHING! They also display everything incorrectly.
As a result, I just made a separate request, and then I mapped it myself. The problem with Yii2 is that if you don't follow what the framework allows, then you need to fight it, although so far everything is ok - everything is written very quickly.

M
mikxa, 2020-03-09
@mikxa

Known problem of duplicates in pagination, in Yii 1 it's the same. MultiSort helps
$dataProvider = new ActiveDataProvider([
'query' => $query,
'sort' => [
'defaultOrder' => ['id' => SORT_DESC],
'enableMultiSort' => true,
],
]);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question