Home > Software engineering >  How to search for a collection with exact same relationship values
How to search for a collection with exact same relationship values

Time:06-05

I have these 3 tables Apparel, Outfit, ApparelOutfit (sample of table structure below). I want to check if an outfit exists using an array of apparel_ids in the ApparelOutfit pivot table. The array of apparel_ids should be exactly the same as the related apparel_ids of the outfit, no more no less. How should I do that?

-- Apparel --
id | name


-- Outfit --
id | is_favorite


-- ApparelOutfit -- (pivot table)
apparel_id | outfit_id

CodePudding user response:

Based on your input via comment

int OUtfit model i have this. public function apparels() { return $this->belongsToMany(Apparel::class) ->withTimestamps() ->as('apparel_outfit') ->orderByPivot('apparel_id'); }

You can try

//Say you have the following apparel ids
$apparelIds = [1,2,3];

$outfits = Outfit::query()
    ->whereHas(
        'apparels', 
        fn($query) => $query->whereIn('id', $apparelIds), 
        '=', 
        count($apparelIds)
    )
    /** If you want to get the records */
    ->get();
    /** If you just want how many outfits exist for the given $apparelIds
     * ->count();
     */

The above query will fetch the Outfit records which are associated with exactly those $apparelIds - no more no less

Eg:

say outfit1 has apparel_ids of [1,2,3] and outfit2 has apparel_ids of [1,2,3,4]

Then only outfit1 will be returned

Laravel Docs - Eloquent Relationships - Querying Relationship Existence

  • Related