@toopay - I could not get the properties to be accessible in the model when set in the view. So I was not able to use Gas\Data(). I did however spend a few hours playing around and figured this out. I think this is a more elegant way to set up the pivot tables, as it’s universal for all my pivot tables and did not require a custom method per pivot table, or a separate entry for each addition.
I still need to do some testing, and I need to add validation to make sure _pivot contains data.
So when creating a record, call function on the model set_pivot. This takes all the table names (lowercase) and the ID if the associated record. Also pass the name of the model, this was just to make the code easier to copy and paste from model to model.
$contents = array(
'name' => 'Heal as One',
'description' => 'Heal yourself and your pet',
'recast' => '20'
);
$newrecord = Model\Skills::make($contents);
$newrecord->set_pivot(array(
'types' => '3',
'pets' => '1',
'weapons' => '1',
'professions' => '3'
), 'skills');
if($newrecord->save()) {
echo 'New Record Saved';
} else {
echo 'Foo not saved. Error were '.$foo->errors('<p class="error">', '</p>');
}
Then in the model add these private fields -
private $_pivot;
private $_model;
The set_pivot function -
function set_pivot($collection, $model) {
$this->_pivot = $collection;
$this->_model = $model;
return $this;
}
Then add this into _after_save() -
if ($this->empty) {
// Record Id
$id = $this->insert_id();
// Insert Into Appropriate Pivot Tables
foreach ($this->_pivot as $key => $value) {
$contents[$key.'_id'] = $value;
$contents[$this->_model.'_id'] = $id;
$class = 'Model\\'.ucfirst($this->_model).'\\'.ucfirst($key);
$class::make($contents)->save(TRUE);
unset($contents);
}
}
Calling make dynamically could not be done without eval before, but thanks to PHP 5.3 this is now valid.
So now it will insert a new entry for any relations that are provided. Obviously this works for me because I follow the default conventions for naming the pivot table foreign keys. I am sure there is a better way to make this worth with the scheme overrides included in the models.