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
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>";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With