samedi 3 août 2019

Merge two Collections in laravel

Need to merge two collections

I have two collections and need to merge them in one collection

these collections was output of two queries using Eloquent

The First Result is like below:

Collection {#350
  #items: array:2 [
    0 => {#342
      +"id": 1
      +"code": "C000215"
      +"name": "Mostafa Mohamed Bayomi"
      +"mobile1": "01228902157"
      +"mobile2": ""
      +"CoachServiceCount": 0
      +"CourseServiceCount": 1
      +"CommunicationCount": 0
    }
    1 => {#337
      +"id": 2
      +"code": "C000216"
      +"name": "Sayed Mohamed Bayomi"
      +"mobile1": "01228902158"
      +"mobile2": ""
      +"CoachServiceCount": 0
      +"CourseServiceCount": 2
      +"CommunicationCount": 0
    }
]
}

The second query result is like below:

Collection {#350
  #items: array:2 [
    0 => {#346
      +"id": 1
      +"code": "C000215"
      +"name": "Mostafa Mohamed Bayomi"
      +"mobile1": "01228902157"
      +"mobile2": ""
      +"CoachServiceAmount": 0.0
    }
    1 => {#340
      +"id": 2
      +"code": "C000216"
      +"name": "Sayed Mohamed Bayomi"
      +"mobile1": "01228902158"
      +"mobile2": ""
      +"CoachServiceAmount": 0.0
    }
]
}

I used this code to merge both collections

$combined = $firstCollection->merge($secondCollection)

I expected below output

Collection {#350
  #items: array:2 [
    0 => {#346
      +"id": 1
      +"code": "C000215"
      +"name": "Mostafa Mohamed Bayomi"
      +"mobile1": "01228902157"
      +"mobile2": ""
      +"CoachServiceCount": 0
      +"CourseServiceCount": 1
      +"CommunicationCount": 0
      +"CoachServiceAmount": 0.0
    }
    1 => {#340
      +"id": 2
      +"code": "C000216"
      +"name": "Sayed Mohamed Bayomi"
      +"mobile1": "01228902158"
      +"mobile2": ""
      +"CoachServiceCount": 0
      +"CourseServiceCount": 2
      +"CommunicationCount": 0
      +"CoachServiceAmount": 0.0
    }
]
}

But I got this output

Collection {#350
  #items: array:4 [
    0 => {#342
      +"id": 1
      +"code": "C000215"
      +"name": "Mostafa Mohamed Bayomi"
      +"mobile1": "01228902157"
      +"mobile2": ""
      +"CoachServiceCount": 0
      +"CourseServiceCount": 1
      +"CommunicationCount": 0
    }
    1 => {#337
      +"id": 2
      +"code": "C000216"
      +"name": "Sayed Mohamed Bayomi"
      +"mobile1": "01228902158"
      +"mobile2": ""
      +"CoachServiceCount": 0
      +"CourseServiceCount": 2
      +"CommunicationCount": 0
    }
    2 => {#346
      +"id": 1
      +"code": "C000215"
      +"name": "Mostafa Mohamed Bayomi"
      +"mobile1": "01228902157"
      +"mobile2": ""
      +"CoachServiceAmount": 0.0
    }
    3 => {#340
      +"id": 2
      +"code": "C000216"
      +"name": "Sayed Mohamed Bayomi"
      +"mobile1": "01228902158"
      +"mobile2": ""
      +"CoachServiceAmount": 0.0
    }
  ]
}



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire