Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define a custom ordering criteria in the relations() method

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?

like image 733
Soph Avatar asked Jul 02 '11 22:07

Soph


1 Answers

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!

like image 111
Soph Avatar answered Nov 15 '22 08:11

Soph