Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

laravel Eloquent relationship using Distinct

I need show data with relationship using DISTINCT.

This is my sql data :

table pochettes

id | 
49 |

table journees

id | formateurs_id | pochettes_id
1  | 3             | 49
2  | 4             | 49
3  | 3             | 49

table formateurs

id | 
3  |
4  |

model Pochette

public function Journees()
{
    return $this->hasMany('App\Journee','pochettes_id');
} 

model Journee

public function Formateurs()
{
    return $this->belongsTo('App\Formateur', 'formateurs_id');
}

I am used this code to show data with distinct formateurs because a Formateur can have many Journee in the same Pochette :

$pochette = Pochette::find(49);
foreach ($pochette->Journees->distinct('formateurs_id') as $formateur) {
            echo $formateur->formateurs_id;
            echo "<br>";
        }

But this code dosn't work, I have this error message

    **BadMethodCallException in Macroable.php line 81:
Method distinct does not exist.**

I would show this result :

3
4

not :

3
4
3
like image 269
Ayed Mohamed Amine Avatar asked Jan 06 '23 10:01

Ayed Mohamed Amine


1 Answers

When you access an Eloquent relationship like a property, you will get an Eloquent Collection. However, distinct() is a Query Builder method and you need access to the Query Builder instance before returning the Collection. If you add () to the end of the relationship, you gain access to the Query Builder instance and can chain those Query Builder methods. In your case, you are actually looking for the groupBy() method and not distinct(). Don't forget to end the query with get().

foreach ($pochette->Journees()->groupBy('formateurs_id')->get() as $formateur) {
    echo $formateur->id ;
    echo "<br>";
}
like image 116
Andy Noelker Avatar answered Jan 23 '23 05:01

Andy Noelker