正在Codeigniter中保存数据映射器关系


Saving datamapper relationship in Codeigniter

我从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默认值(创建和更新)

这种行为正确吗?还是我遗漏了什么?

谢谢!

在文档中:http://datamapper.wanwizard.eu/pages/save.html在在单个调用中保存新对象及其关系将现有对象及其关系保存在单个调用部分中,它解释了datamapper如何处理此问题。

所发生的是save从未在User_profile()上被调用。您需要对尚未持久化的对象调用save(),因此这应该适用于您:

$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();

最后,对象$p的最小值如下

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

调用save方法后,如果数据在此之前不存在,则必须将它们保存为概要文件表中的新条目,或者如果此类行已经存在,则它们必须保存为更新。

希望这能解决你的问题。