title: CoreData Sort by relation
body: <p>My relation is shown on the picture below.</p>
  
  <p><a href="https://i.stack.imgur.com/Y9eDk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Y9eDk.png" alt="CoreData relation"></a></p>
  
  <p>I'd like to sort Events first by those that are in active promotion and then by start date. Promotion is active if current date is between start and end date. Unfortunately, because of CoreData, I'm not able to use transient properties for sorting. In my controller I'm not using a fetch controller.</p>
  
  <p>Is there any way to achieve that?</p>
  
  <p><strong>Update:</strong></p>
  
  <p>I've following sort descriptors:</p>
  
  <pre><code>// First is incorrect
  [NSSortDescriptor(key: "promotion.start", ascending: false), 
  NSSortDescriptor(key: "start", ascending: true)]
  </code></pre>
  
  <p>Predicates (They're ok, though):</p>
  
  <pre><code>let promotionsPredicate =
      NSPredicate(format: "(%@ &gt;= promotion.start &amp;&amp; %@ &lt;= promotion.end) &amp;&amp; " +
                  "(ANY promotion.cities.id == %@)", NSDate(), NSDate(), objectID)
  let eventsPredicate =
      NSPredicate(format: "start &gt;= %@ &amp;&amp; venue.city.id == %@",
                                  NSDate(), objectID)
  
  let subpredicates = [eventsPredicate, promotionsPredicate]                    
  let compoundPredicate NSCompoundPredicate(orPredicateWithSubpredicates: subpredicates)
  </code></pre>
  
  <p>And this is the Request (I'm using CoreStore, but the idea should be clear):</p>
  
  <pre><code>class func pagedEventsForPredicateSortedByInPromoAndStartDate(predicate: NSPredicate,
                                                                descriptors: [NSSortDescriptor],
                                                                fetchOffset: Int,
                                                                fetchLimit: Int) -&gt; [Event] {
  
      return CoreStore.fetchAll(From(Event),
                                Where(predicate),
                                OrderBy(descriptors),
                                Tweak { (fetchRequest) -&gt; Void in
                                  fetchRequest.fetchOffset = fetchOffset
                                  fetchRequest.fetchLimit = fetchLimit
                                  fetchRequest.returnsObjectsAsFaults = false
          }) ?? []
  }
  </code></pre>