benjah
benjah

Reputation: 660

Query Laravel Eloquent many to many where all id's are equal

I making a project based on Laravel and have the tables: companies, attributes, and attribute_company related as Many To Many relation when attribute_company use as a pivot table to connect companies and attributes tables.

I get an array of attribute_id's from the client and I need to get results of the companies that has the whole attributes exactly.

The only solution I found is to query whereHas combined with whereIn inside like this:

Company::whereHas('attributes', function (Builder $query) use ($atts_ids) {
     $query->whereIn('attribute_id', $atts_ids);
})->get();

This query will return companies if at least one attribute_id found (which is not what I am looking for).

It would be great if anybody can make it clearer for me.

Thank you all in advance :)

Upvotes: 6

Views: 774

Answers (1)

Hadi Aghandeh
Hadi Aghandeh

Reputation: 862

One possible solution:

$company = new Company();
$company = $company->newQuery();

foreach($atts_ids as $att_id)
{
    $company = $company->whereHas('attributes', function (Builder $query) use ($att_id) {
        $query->where('attribute_id', $att_id);
    });
}

$company = $company->get();

Upvotes: 5

Related Questions