Home > Back-end >  How to compare array values with one to many relations in laravel
How to compare array values with one to many relations in laravel

Time:09-15

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.

CodePudding user response:

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

$material = Material::has('submaterials', '=', count($submaterials))
  ->whereHas('submaterials', function (Builder $query) use ($submaterials){
        $query->whereIn('id',$submaterials);
    })->get();
  • Related