I'm picking up PHP Active Record and dealing with associations. I have two related objects using a "Has_Many" and "Belongs_to" (parent/child) and trying to create a child record when creating a new parent record (in this case creating a "skin" for my "unit").
class Unit extends ActiveRecord\Model
{
static $has_many = array(
array('skins')
);
}
class Skin extends ActiveRecord\Model
{
static $belongs_to = array(
array('unit')
);
}
I've found both of these threads here: http://www.phpactiverecord.org/boards/4/topics/153 Activerecord-association: create new object (find class)
So I my code currently looks like:
$unit = new Unit();
$unit->name = 'somename';
$unit->description = 'somedescription';
$skinArray = array('name' => $unit->name.' Default Skin');
$unit->create_skins($skinArray);
$unit->save();
The code above is not associating the new skin to the unit in the database or in code though it /is/ placing a new skin record in the database (with a unit_id of NULL). Using "build_skins" doesn't put a Skin record in the database.
I was hoping there was a way to add a "child" to the parent model via the model itself as some other ORM's do. The only way I can do this is to do it explicitly:
$unit = new Unit();
$skin = new Skin();
$unit->name = 'somename';
$unit->description = 'somedescription';
$unit->save();
$skin->unit_id = $unit->id;
$skin->name = $unit->name.' Default Skin';
$skin->save();
Perhaps that is the way it is supposed to be done in PHP ActiveRecord and my expectations are wrong. But I was hoping for a way to do it through the objects that didn't require saving the Parent to the DB with an explicit call first. For example the "Recess" PHP framework would have a simple call on the unit like such: $unit->addSkin($skin);
Do you configurate database connection? Look at gihub examples.
You have to init DB to do this
ActiveRecord\Config::initialize
.