问题描述:

I'm starting with Datamapper and having some errors. I thought if I create an object, a related object and then I save the relationship, both the objects were saves as well.

$u = new User();

$u->where('id', $id)->get();

$p = new User_profile();

$p->name = 'xx';

$u->save($p);

Actually if I do like this, the profile is not saved. And of course not the relationship. If I do something like this:

$u = new User();

$u->where('id', $id)->get();

$p = new User_profile();

$p->save();

$p->name = 'xx';

$u->save($p);

both are saved but the profile is completly empty. None of the parameters are saved but the id and the Datamapper defaults (created and updated)

Is this behavior correct or am I missing something?

Thanks!

网友答案:

In the docs: http://datamapper.wanwizard.eu/pages/save.html under the Save a New object and its Relations in a single call and Save an Existing object and its Relations in a single call sections, it explains how datamapper handles this.

What is going on is that save is never called on the User_profile(). You need to be calling save() on the object that is not yet persisted, so this should work for you:

$u = new User();
$u->where('id', $id)->get();

$p = new User_profile();
$p->name = 'xx';

$p->save($u);
网友答案:
$u = new User();
$u->where('id', $id)->get();

//passing the user object $u to the user_profile object ensures that
//data-mapper fills $p with any related information in the database if that exists
//or just the id attribute for the relationship.
//This way, $p will not be empty even though its fields might not b complete,
//but the relating attribute which should be 'user_id' will have a valid value
//in the 'profiles' table
$p = new User_profile($u);

$p->name = 'xx';

$u->save();
$p->save();

At the end of this, the object $p will now have the following value at the minimum

echo $p->user_id   //prints out $id;
echo $p->name      //prints out xx.

After calling the save method, they must definitely be saved as a new entry in the profiles table if the data does not exist before or as an update if the such row already exists.

Hope this solves your problem.

相关阅读:
Top