I am trying to save multiple related child records on a single transaction.
I am sending over the data as an array on the users form
Parent Model: Users
public $id;
.....
public function initialize()
{
$this->hasMany('id', 'UsersCompliance','userId',array(
'alias' => 'usersCompliance',
'foreignKey' => array(
'action' => Relation::ACTION_CASCADE
)));
}
Child Model: Compliance
public $id;
public $userId;
public $key;
public $value;
public function initialize()
{
$this->belongsTo('userId','Users','id');
}
I would like a way to dynamically create new key=>value pairs and/or update existing key value pairs multiple at a time. Was able to get a single to update a time using this logic here.
foreach($this->request->getPost('compliance') as $key => $value){
$comp = new UsersCompliance();
$comp->userId = $user->id;
$comp->name = $key;
$comp->value = $value;
$user->usersCompliance = $comp;
}
}
Now obviosuly i have already set a usersComplaince, but by definition of the model this should accept multiple no? This also has the undesired affect of simply creating a new line item instead of updating an existing one if it already exists.
I can add in some logic to test in every iteration and solve the issue of duplication. but i can't get it to save more than one record at a time. soemthing like the following woudl be nice.
// if doesn't match an existing add to the new save result set etc.
$user->usersCompliance[] = $comp;