monk pierpa Sun Mar 17 12:37:15 -0400 2013

Subject: Insert with has many through relationship

Hi guys,
I'm fairly new to ActiveRecord and I've not not well understood the relationship "has_many through".
I've correctly (i hope) declared relationship on my model, but i don't know how to quickly insert records using this relationship.
I try to explain better:
I've these models:

class Manager extends ActiveRecord\Model
{
static $has_many = array(
array('regions', 'through' => 'manager_zones')
);
}
class ManagerZone extends ActiveRecord\Model {
static $belongs_to = array(
array('regions'),
array('managers')
);
}
class Region extends ActiveRecord\Model {
static $has_many = array(
array('managers', 'through' => 'manager_zones'),
);
}

So i think, in this way, to have declared a many to many relationships between managers and regions through ManagerZone (manager_zones table).

So i've created a controller to try to insert all the regions associated with a manager. Associated regions come to controller as comma separated values in a param named "regions"

public function create_new(){
$manager= new Manager();
try{
$this->setObjectFromRequest($manager, 'manager', $this->model_attributes);
}catch (exception $err){
echo "ERROR $err<br>\n";
exit;
}
$regions = explode(',',$_REQUEST['regions']);
foreach($regions as $region_id){
$region = new Region();
$region->id = $region_id;
$manager->regions[] = $region;
}
$manager->save();
}

But this doesn't work. I've tried also adding only id to $manager->regions[], but also this doesn't work! :(
I've searched on the web, but i've not found solutions.

Can anyone help me?

Thanks in advance.

#Pp