how do related objects (foreign keys, one-to-many) get ORDERED ?

33 views
Skip to first unread message

jon v

unread,
Sep 5, 2012, 7:13:40 PM9/5/12
to rose-db...@googlegroups.com
hello!  i am new to Rose::DB::Object and am liking it so far. very useful.  i have a question though about the ordering of "nested" objects created by linked tables.

for example, if i have a class Foo::Question which has a one to many relationship with class Foo::Option, my code is correctly returning an array with something like @options = $question->options (that is, @options ends up with an array of Foo::Option objects, each of which have question_id pointing to the id of $question).

however, how is this array ordered?  is the ordering determined solely by the primary key (id) of Foo::Option?  or can i pass an optional field to use to order the array, such as if i add a column "delta" to Foo::Option which is the relative sort order.

the (obvious?) reason i would like to know this is so i can control (and change easily) the order options are given.  in my case, this is to build a structure for presenting multiple choices below a question.  (e.g. "What is your favorite color?" -> [ blue, red, none of the above ]  ... does not work well if i add a new Foo::Option for "green" to the list)


thank you very much for your help, and i hope i simply did not miss this in the docs!
-jon

John Siracusa

unread,
Sep 5, 2012, 7:20:33 PM9/5/12
to rose-db...@googlegroups.com
On Wed, Sep 5, 2012 at 7:13 PM, jon v <sito...@gmail.com> wrote:
> for example, if i have a class Foo::Question which has a one to many
> relationship with class Foo::Option, my code is correctly returning an array
> with something like @options = $question->options (that is, @options ends up
> with an array of Foo::Option objects, each of which have question_id
> pointing to the id of $question).
>
> however, how is this array ordered? is the ordering determined solely by
> the primary key (id) of Foo::Option? or can i pass an optional field to use
> to order the array, such as if i add a column "delta" to Foo::Option which
> is the relative sort order.

Try setting sort_by in the manager_args attribute of the relationship:

http://search.cpan.org/dist/Rose-DB-Object/lib/Rose/DB/Object/Metadata/Relationship/OneToMany.pm#manager_args

-John

jon v

unread,
Sep 5, 2012, 7:22:53 PM9/5/12
to rose-db...@googlegroups.com
wow!  excellent. this looks like just the thing.
thanks very much.

guess i need to RTFM... (or do a better job searching it)

-jon
Reply all
Reply to author
Forward
0 new messages