1

我从 Datamapper 开始并且有一些错误。我想如果我创建一个对象、一个相关对象然后保存关系,那么这两个对象也都被保存了。

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

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

$u->save($p);

实际上,如果我这样做,则不会保存配置文件。当然不是关系。如果我做这样的事情:

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

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

$u->save($p);

两者都已保存,但配置文件完全为空。没有保存任何参数,但 id 和 Datamapper 默认(创建和更新)

这种行为是正确的还是我错过了什么?

谢谢!

4

2 回答 2

1

在文档中:http ://datamapper.wanwizard.eu/pages/save.html在Save a New object and its Relations in a single callSave an Existing object and its Relations in a single call部分下,它解释了 datamapper 如何处理这个。

正在发生的事情save是从未在User_profile(). 您需要调用save()尚未持久化的对象,因此这应该适合您:

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

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

$p->save($u);
于 2012-01-12T19:22:19.677 回答
1
$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();

在此结束时,对象 $p 现在将至少具有以下值

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

调用 save 方法后,如果数据之前不存在,则必须将它们作为新条目保存在配置文件表中,如果这样的行已经存在,则必须将它们保存为更新。

希望这能解决您的问题。

于 2012-01-12T22:25:58.683 回答