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);
I'm not really familiar with php active record, but in my experience (same problem was when I was using Doctrine and tried to add child views and there also was null, before I persisted parent and child to database). I think that phpactiverecord does not have this functionality, so the solution that I will suggest - create manually methods in Models, like Unit::addSkin(Skin $skin), that will have something like this inside:
Basically logic like that. But I cannot say that this aproach is good or even neutral practive. Just this is the way you can do such things in Doctrine.
Also, you tried Propel? If you like active record, I think you'll find it pretty interesting.