Relations: Not Standard Sort Order

Hi everyone,

a little bit complex question.

I’ve “Families” model. Inside this one I have define this relation




	public function relations()

	{

		return array(

		    'members'=>array(self::HAS_MANY, 'Link', 'family_id', 'order'=>'type ASC')

		);

	}



that helps me to get all family member.

For example:

  • Paul | Child

  • Antoine | Husband

  • Laura | Wife

  • Robert | Child

I would have this array of “Link” (this is the model I’ve called) sorted in this way:

First of all Husband, next the Wife and finally all the Childs, sorted by birth year.

Model "Link" have following table structure

id [int] | family_id [int] | member_id [int] | type [varchar(4)]

type can be ‘HUSB’ or ‘WIFE’ or ‘CHIL’

Is it possibile to define something like function usort does in PHP?

http://php.net/manual/en/function.usort.php

Thanks

You could sort by a SQL expression, like:




'order'=>"(CASE type WHEN 'HUSB' THEN 1 WHEN 'WIFE' THEN 2 WHEN 'CHIL' THEN 3 END) ASC"



but I would just advise creating a dictionary like relation ("types") and add a number column there by which you could sort.

Very thanks!

And now, if I would childs sorted by birth date.

Maybe I have to create a function inside the controller to customize my set of member?

If I have $child1, $child2, I have to check different things.




$birth1 = $child1->getEvent('BIRT');

$birth2 = $child2->getEvent('BIRT');



both return an array of events. In this case the size of these could be 0 or 1, of couse.

If size of $birth1 is 1 and size of birth2 is 0 then $child1 < $child2 (in my logic criteria).

If both sizes are then I’ve to compare $birth1[0]->julianday and $birth2[0]->julianday.

How can I do? I could create a function i my Families model like this




public function sortedMembers() {

       // use define relation

       $members=$this->members;

       // sort array with custom cmp function

       usort($members, "cmp");

       

       return members;

}



Better ways?