Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 :)

like image 570
benjah Avatar asked Sep 03 '19 06:09

benjah


1 Answers

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();
like image 53
Hadi Aghandeh Avatar answered Nov 06 '22 13:11

Hadi Aghandeh