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.
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.
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.
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 }
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)
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?