Tim Riggins Mon Oct 03 18:53:59 -0400 2011

Subject: many-to-many association from the wiki

Hi all!

Just a quick question: considering the many to many association on the wiki (http://www.phpactiverecord.org/projects/main/wiki/Associations), which is the 'find' insctruction, using the models (not find_by_sql), that retrieves all the orders of a specified amount, let's say 10.0, for the user Brad Pitt ? :)

Thanks a lot for your answer.

Tim


Andrew Smart Thu Oct 06 16:01:35 -0400 2011

Assuming the following class structure...

1 class User extends ActiveRecord\Model {
2    static $has_many = array(array('orders'));
3 }
4 
5 class Order extends ActiveRecord\Model {
6    static $has_one = array(array('user'));
7 }

... the following will do the trick

1 $user = User::find_by_name("Brad Pitt");

Orders by this user can then be accessed simply by the following

1 $user->orders

Alternatively you can do the following

1 $orders = Order::all(array(
2    'joins' => array('user'),
3    'conditions' => array("user.name = ? AND order.amount = ?", "Brad Pitt", 10)
4 ));
Tim Riggins Fri Oct 07 15:46:16 -0400 2011

Thanks a lot for your answer Andrew but actually I was talking about a many-to-many association (has_many through) with the following class structure :

class Order extends ActiveRecord\Model {
   static $has_many = array(
      array('payments'),
      array('users', 'through' => 'payments')
   );
}

class Payment extends ActiveRecord\Model {
   static $belongs_to = array(
      array('user'),
      array('order')
   );
}

class User extends ActiveRecord\Model {
   static $has_many = array(
      array('payments')
   );
}

Do you think you can help me?

Tim Riggins Wed Oct 19 03:28:52 -0400 2011

Hi guys!

So, nobody has any idea about it? No one is talking about that on internet, maybe it's not possible to do it with AR...

If you guys have a workaround, could you please share it?

Thanks a lot!

(1-3/3)