I have a 3 level Models structure:
Model_Race has_many Model_Class
Model_Class has_many Model_Driver
Now, imagine Model_Class and Model_Driver have an order_index property to keep them in order.
Is there a clean way to get a Race and have the Class and Driver's sorted correctly?
The documentation clearly shows this, I somehow missed it:
$race = Model_Race::find($id, array(
'related' => array(
'class' => array(
'order_by' => array('order_index' => 'asc'),
'related' => array(
'driver' => array(
'order_by' => array('order_index' => 'asc'),
)
)
)
)
)
);
(my preferred method over array syntax above)
$race = Model_Race::query()
->related('race.class')
->related('race.class.driver)
->order_by('race.class.order_index', 'asc')
->order_by('race.class.driver.order_index', 'asc')
->get();
You can set up the relationships in the model so that this happens by default:
Race Model:
protected static $_has_many = [
'classes' => [
'conditions' => [
'order_by' => [
'order_index' => 'asc'
]
]
]
];
Class Model:
protected static $_has_many = [
'drivers' => [
'conditions' => [
'order_by' => [
'order_index' => 'asc'
]
]
]
];