我有一个3级模型结构:
Model_Race has_many Model_Class
Model_Class has_many Model_Driver
现在,想象一下Model_Class和Model_Driver有一个order_index属性来保持它们的顺序。
是否有一种干净的方式来获得比赛并正确分类和驱动程序?
答案 0 :(得分:7)
documentation清楚地表明了这一点,我不知怎的错过了它:
$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'),
)
)
)
)
)
);
(我上面的数组语法首选方法)
$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();
您可以在模型中设置关系,以便默认情况下发生这种情况:
种族模型:
protected static $_has_many = [
'classes' => [
'conditions' => [
'order_by' => [
'order_index' => 'asc'
]
]
]
];
班级模特:
protected static $_has_many = [
'drivers' => [
'conditions' => [
'order_by' => [
'order_index' => 'asc'
]
]
]
];