vendredi 29 décembre 2017

Laravel merge multiple collections and sort by corresponding datetime field

I have multiple collections merging into one, then sorting that one by datetime to ultimately create a timeline between the collections.

Heres the catch, the datetime columns to sort are different names.

Is there anything I can do to make this cleaner - possibly attach the foreach loop with the ->merge? Looks ugly with the foreach loop. note: code below works but I feel it's a lazy way out and might be slow with more items in the collection.

// Create timeline, sortby creation datetimes.
$TimelineItems = collect();

$TimelineItems = $Appointments->merge($lead->SalesResult);
foreach ($TimelineItems as $key => $TimelineItem) {
    if(!empty($TimelineItem->appointment_created)) {
        $TimelineItems[$key]->created_at = $TimelineItem->appointment_created;
    }
    if(!empty($TimelineItem->salesresult_created_timestamp)) {
        $TimelineItems[$key]->created_at = $TimelineItem->salesresult_created_timestamp;
    }
}
$TimelineItems = $TimelineItems->sortByDesc('created_at');
dd($TimelineItems);



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire