Search code examples
fuelphp

How to sort related children Models using FuelPHP's ORM


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?


Solution

  • The documentation clearly shows this, I somehow missed it:

    Find Array Syntax

    $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'),
                        )
                    )
                )
            )
        )
    );
    

    Using Query Method Chaining Syntax

    (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();
    

    Build it into the Model

    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'
                ]
            ]
        ]
    ];