lundi 4 avril 2016

laravel5.1 return ordered collection of items

I would like to return the result of this operation in an ordered eloquent collection. First of all, I know this will get ugly since there is no relation between the items. Here's my database design:

ticket_events (can store some events like "ticket closed", "ticket moved to supporter XY" etc.)
id|ticket_id|...|...|created_at

ticket_replies (stores all "replies" made to a ticket)
|id|ticket_id|text|...|created_at

Now let's say a user created a ticket and a supporter answered to this ticket and user will close ticket in the end. This will produce this entrys into database.

->ticket_event (ticket opened by user X)
->ticket_replie (first question made by user X)
->ticket_replie (answer from supporter)
->ticket_event (ticket closed by user X)

There is no direct connection between replies and events, because there's no logical relationship between them. Ordering them by using "created_at" won't work, because the timestamp will be the same. I think ordering them and returning a the ordered collection will be some ugly work to do. Here's what I tried already.

class ticketHelper
    {

   var $ticket_replies;
   var $ticket_events;

   function orderReplies()
   {
      $ticket_replies = $this->ticket_replies;
      $ticket_events = $this->ticket_events;

      $events_replies = $ticket_events->merge($ticket_replies)->sortByDesc('created_at');

      $filtered = $events_replies->sort(function($itemA, $itemB)
      {
        if($itemA->created_at == $itemB->created_at)
        {
            if(is_a($itemA,'ticket_event'))
            {
              return true;
            }
            else
            {
              return false;
            }
        }
            else
            {
                return (($itemA->created_at >= $itemB->created_at) && ($itemA->created_at <= $itemB->created_at));
            }
      });
      return $filtered;
      }
    }

Some eloquent expert here maybe giving me a little bit help to get this solved, so I get the collection returned in this order:

->ticket_event (ticket opened by user X)
->ticket_replie (first question made by user X)
->ticket_replie (answer from supporter)
->ticket_event (ticket closed by user X)



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire