Love Fuel?    Donate

FuelPHP Forums

Ask your question about FuelPHP in the appropriate forum, or help others by answering their questions.
ORM has_many order by
  • Can I somehow define in ORM model has_many relation to sort related records like this:

    SELECT * FROM tablename ORDER BY -position DESC

    I have table departments which has many users. I would like to sort users within department by sort_order field. This field can be either number or NULL. I would like to have NULLs at the end of the list. MySQL has a syntax by sorting nulls at the end by adding "-" before sorting field name and using DESC. Taken from here: http://stackoverflow.com/questions/2051602/mysql-orderby-a-number-nulls-last

        protected static $_has_many = array(
            'internalusers' => array(
                'key_from' => 'id',
                'model_to' => 'Model_Profile',
                'key_to' => 'internal_department_id',
                'cascade_save' => true,
                'conditions' => array(
                    'order_by' => array(
                        '-sort_order' => 'DESC'
                    )
                ),
            ),
        );

    Tried it this way but won't work... Probably not supported in current ORM implementation?
  • Correct, that is not supported.

    As the stackoverflow post already mentions, what you do is

    SELECT * FROM tablename ORDER BY (0 - position) DESC

    Which is ordering by a dynamic expression. You could try to get this in with a DB::expr(), but you can't define that as part of the property, and I'm not sure it will work there.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

In this Discussion