7

I have a model A that has a relationship of type HAS_MANY with model B.

B's attributes are:

id,
user_id,
message,
date,
parent_message_id

I need elements of model B to be ordered by date (descending), but in case the parent_message_id is different from null, the date to be taken into consideration should be the date corresponding to parent_message_id.

Is it possible to customize the criteria used to order the relation?

double-beep
  • 5,031
  • 17
  • 33
  • 41
Soph
  • 2,895
  • 5
  • 37
  • 68
  • can you test for the condition first and use a different relation or scope depending on the result? – ldg Jul 04 '11 at 14:46
  • @ldg I am not quite sure if i get what you mean, could you be a little more specific? Or provide an example? Most thankful for your reply! – Soph Jul 04 '11 at 17:21
  • If you want to change the sort order of all the results and can test for whatever condition that may require, you can add a scope as appropriate to change the sort order. It may or may not make sense for your need, see: http://www.yiiframework.com/doc/guide/1.1/en/database.arr#relational-query-with-named-scopes – ldg Jul 04 '11 at 17:36

2 Answers2

10

Ok, i solved this the following way: model A HAS_MANY model B, therefore, i redefined the relationships method to the following:

public function relations()
{
    return array(
        'messages' => array(self::HAS_MANY, 'WallMessages', 'liga_id',
            'condition'=>'specific_post.parent_message_id IS NULL', 
            'order'=>'specific_post.date DESC', 
            'alias'=>'specific_post'),
    );
}

Therefore, I only compare the date of those messages with no parent id. The downside is that I have to access each post's "child messages"... but well, couldn't find another workaround. Thanks all for your help!

Soph
  • 2,895
  • 5
  • 37
  • 68
0

I think it is only possible to sort elements according to the same column. However there might be a database ninja that could help you.

In an perfect world you could use the afterFind() method for any customization at any level, not only sorting, but also changing some values for others. It is not as fast as a plan order, maybe, but this way you release the MySQL server from a little load. Plus it is called automatically. Cheers

Sergi Juanola
  • 6,531
  • 8
  • 56
  • 93