samedi 2 juin 2018

How to intersect two Laravel object collections that feature different objects, but share a common key

If I have two collections of objects in Laravel which aren't the same object type, but feature a matching column, how can I intersect them by that specific column (property)?

Collection of Objects 1

//Words
{'id', 'name'}

Collection of Objects 2

//Words Used
{'id', 'name', 'count'}

The id columns aren't the same (there is an auto increment index on each table) but the name columns are the same.

Example of the two collections:

//Collection of Words
{1, 'test'},
{2, 'this'},
{3, 'list'}

//Collection of Words Used
{12, 'this', 1},
{13, 'is', 1},
{14, 'a', 1},
{15, 'test', 1},
{16, 'sentence', 1}

I want to keep collection 2 (Words Used) but filter it (intersect it) with collection 1 but ONLY on the name column. So my result should look like:

{12, 'this', 1},
{15, 'test', 1}

A normal intersect in Laravel would be something like

$wordsUsed = $wordsUsed->intersect($wordsList)

But doing it that way seems to compare the entire object, and since the properties aren't the same between the objects, it never has a match. How do I specify it only works on one column?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire