【发布时间】:2014-11-10 10:21:39
【问题描述】:
我正在尝试利用 CakePHP 的 saveMany 功能(带有关联的数据功能),但是我正在创建重复记录。我认为这是因为 find() 查询没有找到作者,因为事务尚未提交到数据库。
这意味着如果有两个作者具有相同的用户名,例如,在电子表格中,那么 CakePHP 不会将第二个与第一个相关联,而是创建两个。我为这篇文章编写了一些代码:
/*
* Foobar user (not in database) entered twice, whereas Existing user
* (in database) is associated
*/
$spreadsheet_rows = array(
array(
'title' => 'New post',
'author_username' => 'foobar',
'content' => 'New post'
),
array(
'title' => 'Another new post',
'author_username' => 'foobar',
'content' => 'Another new post'
),
array(
'title' => 'Third post',
'author_username' => 'Existing user',
'content' => 'Third post'
),
array(
'title' => 'Fourth post', // author_id in this case would be NULL
'content' => 'Third post'
),
);
$posts = array();
foreach ($spreadsheet_rows as $row) {
/*
* This query doesn't pick up the authors
* entered automatically (see comment 2.)
* within the db transaction by CakePHP,
* so creates duplicate author names
*/
$author = $this->Author->find('first', array('conditions' => array('Author.username' => $row['author_username'])));
$post = array(
'title' => $row['title'],
'content' => $row['content'],
);
/*
* Associate post to existing author
*/
if (!empty($author)) {
$post['author_id'] = $author['Author']['id'];
} else {
/*
* 2. CakePHP creates and automatically
* associates new author record if author_username is not blank
* (author_id is NULL in db if blank)
*/
if (!empty($ow['author_username'])) {
$post['Author']['username'] = $row['author_username'];
}
}
$posts[] = $post;
}
$this->Post->saveMany($posts, array('deep' => true));
有什么方法可以实现这一点,同时保持交易?
【问题讨论】:
-
你能展示一个生成数据的样本来保存吗?另外,当主要模型数据属于帖子时,您为什么要通过
Author模型保存?附言。请始终提及您的确切 CakePHP 版本并相应地标记您的问题! -
您正在插入新行,因为您没有要保存到的主模型的主键。有 id 的数据是编辑,没有的是插入。
-
@ndm 通过作者模型保存是一个错字。我正在保存新行,但它应该只发生一次。在插入(刚刚插入的)用户之后,查询应该选择用户已经存在于数据库中,并使用 ID 而不是复制用户。我相信我需要嵌套事务,但不确定是否有更好的方法。
-
所以你有一个
Author hasMany Posts关联?而您真正想做的是保存许多帖子,其中多个帖子可以属于单个(不一定是现有的)用户?
标签: php cakephp cakephp-2.5