Aug 21

Cakephp 学习日志 (二) 不指定

bkkkd , 07:54 , 开发应用 , 评论(0) , 引用(0) , 阅读(39483) , Via 本站原创 | |

保存关联对象
请记住一件非常重要的事情,当保存对象时,很多时候需要同时保存关联对象,比如当我们保存Post对象和它关联的Comment对象时,我们会同时用到Post和Comment两个model的操作。

抽象出来说,当关联的两个对象都没有持久化(即未保存在数据库中),你需要首先持久化主对象,或者是父对象。我们通过保存Post和关联的一条Comment这个场景来具体看看是如何操作的:

//------------Post Comment都没有持久化------------  
  
/app/controllers/posts_controller.php (partial)  
function add()  
{  
    if (!emptyempty($this->data))  
    {  
        //We can save the Post data:  
        //it should be in $this->data['Post']  
          
        $this->Post->save($this->data);  
  
        //Now, we'll need to save the Comment data  
        //But first, we need to know the ID for the  
        //Post we just saved...  
  
        $post_id = $this->Post->getLastInsertId();  
  
        //Now we add this information to the save data  
        //and save the comment.  
  
        $this->data['Comment']['post_id'] = $post_id;  
  
        //Because our Post hasMany Comments, we can access  
        //the Comment model through the Post model:  
  
        $this->Post->Comment->save($this->data);  
  
    }  
}  

换一种情形,假设为现有的一篇Post添加一个新的Comment记录,你需要知道父对象的ID。你可以通过URL来传递这个参数或者使用一个Hidden字段来提交。

/app/controllers/posts_controller.php (partial)  
//Here's how it would look if the URL param is used...  
function addComment($post_id)  
{  
    if (!emptyempty($this->data))  
    {  
        //You might want to make the $post_id data more safe,  
        //but this will suffice for a working example..  
  
        $this->data['Comment']['post_id'] = $post_id;  
  
        //Because our Post hasMany Comments, we can access  
        //the Comment model through the Post model:  
  
        $this->Post->Comment->save($this->data);  
    }  
}  

如果你使用hidden字段来提交ID这个参数,你需要对这个隐藏元素命名(如果你使用HtmlHelper)来正确提交:

假设日志的ID我们这样来命名$post['Post']['id']

hidden('Comment/post_id', array('value' => $post['Post']['id'])); ?>

这样来命名的话,Post对象的ID可以通过$this->data['Comment']['post_id']来访问,同样的通过$this->Post->Comment->save($this->data)也能非常简单的调用。

当保存多个子对象时,采用一样的方法,只需要在一个循环中调用save()方法就可以了(但是要记住使用Model::create()方法来初始化对象)。
内文分页: [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12] [13] [14] [15] [16]
Tags:
发表评论
表情
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
emotemotemotemotemot
打开HTML
打开UBB
打开表情
隐藏
记住我
昵称   密码   游客无需密码
网址   电邮   [注册]