【问题标题】:Saving datamapper relationship in Codeigniter在 Codeigniter 中保存数据映射器关系
【发布时间】:2012-01-12 19:04:21
【问题描述】:

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

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

谢谢!

【问题讨论】:

  • 听起来好像您可能没有正确设置模型。你也可以发一下吗?
  • 不,模型应该没问题,因为它适用于某些情况。我认为这与答案有关。谢谢!

标签: php codeigniter codeigniter-datamapper


【解决方案1】:

在文档中: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);

【讨论】:

  • 所以我误解了文档。感谢您的回答,我会解决并回复。谢谢!
【解决方案2】:
$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 方法后,如果数据之前不存在,则必须将它们作为新条目保存在配置文件表中,如果此类行已存在,则必须将其保存为更新。

希望这能解决您的问题。

【讨论】:

  • 非常感谢。我还没有尝试,但它似乎很正确。
猜你喜欢
  • 2014-04-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-07
  • 1970-01-01
  • 2011-07-11
  • 1970-01-01
  • 2011-06-14
相关资源
最近更新 更多