tzvika ofek Tue Oct 12 04:17:39 -0400 2010

Subject: Add conditions to associations dynamically

Hi, i think this option is missing and needed -
i need to apply conditions to associations.
Suppose i got users has many orders.

I need to do something like that:
$user_orders->orders(array('conditions' => 'statusID > 0'));
but of course it doesn't work this way...

Any suggestions?


Keith Thibodeaux Sat Oct 16 19:20:49 -0400 2010

In your User model, instead of

static $has_many = array (
  array('orders')
);

put this:

static $has_many = array (
  array('orders', 'conditions' => 'statusID > 0')
);

From now on, anytime you call $user->orders it will sort with statusID > 0.
If you need only a few more sorting options, I'm assuming you'd want to view orders with statusID = 0, do something like this:

static $has_many = array (
  array('orders', 'conditions' => 'statusID > 0'),
  array('complete_orders', 'conditions' => 'statusID = 0')
);

You could then call $user->orders or $user->complete_orders.

I also wish what you want was able to be done in the current versions, but this is a temporary work around that will suite most situations.

tzvika ofek Sun Oct 17 02:36:01 -0400 2010

Thanks for the idea , but as you say , it will be better if it can be done for a single query and effect all queries.

Son Vu Fri Jan 13 22:51:25 -0500 2012

txvika: Have you found way to sort the results of $user_orders yet? I am trying to figure out the same problem. I want to be able to resort the results even after it's been defined in the 'has_many' attribute.

(1-3/3)