How to compare array values with one to many relations in laravel

Viewed 39

I have an input array of submaterials. $submaterials = [1, 2,3]

I am using lumen framework connected with mysql. I have a one to many relation with material and submaterial table. That's a material can have many submaterials.

Here my requirement is to get materials which have same submaterials in input. I only need to get materials which have exact same number of submaterials and same submaterials in input array

This is the query i have added

$submaterials_array = [12,13];
$otherrequests = for ($i = 0; $i < sizeof($submaterials_array); $i++) 
{
    $id = $submaterials_array[$i];
    Offerrequest::whereHas('submaterialprops', function ($q) use ($id) {
        $q->where('submaterial_id', $id);
  });
}
$otherrequests = $otherrequests->get();

I have tried the query and I got a list of all offerrequests with submaterial id='12,13'. But I want to get only rows which have exact these submaterials(one to many relation). That means it should not return rows with submaterial 12,13,14 or 12,13,14,15,16.

1 Answers

Assuming you have a material model and your one to many relationship defined on the material model is called submaterials and that $submaterials is the array of ids. You could try using https://laravel.com/docs/9.x/eloquent-relationships#querying-relationship-existence

There may be other ways to do this but you could dynamically build the query by looping through the submaterials and adding a whereHas for every submaterial.

$materialQuery = Material::has('submaterials', '=', count($submaterials));

foreach($submaterials as $submaterial){
    $materialQuery->whereHas('submaterials', function (Builder $query) use ($submaterial){
        $query->where('id',$submaterial);
    });
}   

$material = $materialQuery->get();
Related