Ad
BelongsToMany Relation. How To Get Unique Rows
I have next 'member_companies'
table in DB:
And in model Member has a relation :
public function companies()
{
return $this->belongsToMany(Company::class, 'member_companies');
}
And it return me all companies with dublicates. For example, Member::find(238)->companies->pluck('id')
return
[
6,
5,
7,
2,
10,
8,
4,
13,
14,
10,
8,
13
]
But I want only unique items. Like
[
6,
5,
7,
2,
10,
8,
4,
13,
14,
]
How can I do it with eloquent relations?
Ad
Answer
I found next solution:
public function companies()
{
$relation = $this->belongsToMany(Company::class, 'member_companies');
$relation->getQuery()->getQuery()
->joins[0]->table = \DB::raw('(SELECT DISTINCT member_id, company_id FROM member_companies) as member_companies');
return $relation;
}
But maybe there is more delicate variant of this code?
Ad
source: stackoverflow.com
Related Questions
- → "failed to open stream" error when executing "migrate:make"
- → October CMS Plugin Routes.php not registering
- → OctoberCMS Migrate Table
- → OctoberCMS Rain User plugin not working or redirecting
- → October CMS Custom Mail Layout
- → October CMS - How to correctly route
- → October CMS - Conditionally Load a Different Page
- → Make a Laravel collection into angular array (octobercms)
- → In OctoberCMS how do you find the hint path?
- → How to register middlewares in OctoberCMS plugin?
- → Validating fileupload(image Dimensions) in Backend Octobercms
- → OctoberCMS Fileupload completely destroys my backend
- → How do I call the value from another backed page form and use it on a component in OctoberCms
Ad