Save a new child AR object the OOP way


$user = User::Model()->findByBk($id);

$thing = new Thing();

$thing->prop = 'value';

$thing->user_id = $user->id; // this libe feels like SQL, not AR OOP

$thing->save();

Line 4 above makes this feel like a mixture of OOP and SQL approaches.

A pure OOP approach would hide explicit manipulation of $thing’s FK. I would have though the last two lines ought to be something like:


$user->things[] = $thing;

$user->save();

Or something a bit more complicated.

The Definitive Guide chapter on Relational AR does not mention saving new children. What’s the right way to do it?

An implementetation of the Active Record pattern, by its nature, is always built on a mixture of OO and relational paradigms. Try with-related-behavior for a more object-oriented approach.