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.

Some DevGuy 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.

Hamad Alfahad Sun Mar 11 14:51:47 -0400 2012

I had the same concern a whle ago and posted a question on here: http://stackoverflow.com/questions/9453967/php-activerecord-array-of-objects-what-next

Finally, I created a helper function as follows that lets me fetch AR objects from a result set using basic PHP array manipulation:

 1 function search_object($array, $property, $property_value)
 2 { 
 3     foreach ($array as $key => $value) { 
 4         $return = $array[$key]; 
 5 
 6         if ($return->$property == $property_value) { 
 7             return $return; 
 8         } 
 9     } 
10     return FALSE;
11 }
Manuel de la Higuera Wed Jun 27 09:45:13 -0400 2012

This post is pretty old but I ran into this during these days. In spite this is a dirty solution I find this to be easy to refactor when needed:

1 public function orders_by_status($status=0) {
2     $temp = new ActiveRecord\HasMany(array(
3       'temporary',
4       'class_name' => 'Order',
5       'conditions' => sprintf("statusID > %u", $status)
6     ));
7     return $temp->load($this);
8 }

(1-5/5)