mardi 25 septembre 2018

Laravel-How to merge two collections when one column is common in both collection?

I am using Laravel 5.6.38.

I have two collections.

Collection 1

[{
"link": "http://example.com/videos/1",
"created_at": "2018-09-20 05:14:10",
"description": "some desc 1",
"video_id": 1,
"priority": "2",
"identifiedBy": "x",

},
{
"link": "http://example.com/videos/2",
"created_at": "2018-09-20 05:14:10",
"description": "some desc 2",
"video_id": 2,
"priority": "3",
"identifiedBy": "x",
}]

Collection 2

[{
"video_id": 1,
"qatagger": "Mr. X"
}]

Expected result

[{
"link": "http://example.com/videos/1",
"created_at": "2018-09-20 05:14:10",
"description": "some desc 1",
"video_id": 1,
"priority": "2",
"identifiedBy": "x",
"qatagger": "Mr. X"
},
{
"link": "http://example.com/videos/2",
"created_at": "2018-09-20 05:14:10",
"description": "some desc 2",
"video_id": 2,
"priority": "3",
"identifiedBy": "x",
}]

I tried $collection1->merge($collection2), gets result

[{
"link": "http://example.com/videos/1",
"created_at": "2018-09-20 05:14:10",
"description": "some desc 1",
"video_id": 1,
"priority": "2",
"identifiedBy": "superadmin"
},
{
"link": "http://example.com/videos/2",
"created_at": "2018-09-20 05:14:10",
"description": "some desc 2",
"video_id": 2,
"priority": "3",
"identifiedBy": "superadmin"
},
{
"video_id": 1,
"qatagger": "Mr. x"
}]

Is there anyway I can get the expected result with out using any loop?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire