好的,所以在测试之后,看起来 Propel 将在一个事务中执行如下代码,但不是一个数据库命中。这可能是使用 Propel 执行此操作的最有效方法,但是:
$postobj = new Post();
$postobj->setTitle("First title");
$postobj->setContent("First title");
$category_id = array(8,9,17,39)
for ($i=0,$l=sizeof($category_id); $i<$l; ++$i) {
$cp = new CategoryPost();
$cp->setPost($postobj);
$cp->setCategoryId($category_id[$i]);
$postobj->addCategoryPost($cp);
}
$postobj->save(); // this will save the Post AND the CategoryPost objects
更新
如果您想将此代码放入允许您传递一些数据并保存它的辅助函数中,那么您可以这样做(警告:这是未经测试的,小心):
class Post extends BasePost
{
public function saveAllData($data, PropelPDO $con = null) {
// might want to do some audits on input..
$this->fromArray($data); // catches most data
// add relationships
if (isset($data['categoryIds']) && is_array($data['categoryIds'])) {
for ($i=0,$l=sizeof($data['categoryIds']); $i<$l; ++$i) {
$cp = new CategoryPost();
$cp->setPost($this);
$cp->setCategoryId($data['categoryIds'][$i]);
$this->addCategoryPost($cp);
}
}
// do the save
// NOTE: you might want to do validations first, etc
return $this->save($con);
}
}
然后你会像这样从你的脚本中调用它:
...
$data = array(
"ColumnName"=>"value", // NOTE: the ColumnName must match the Propel column
...
"CategoryIds"=>array(2,3,4,5)
);
$post = new Post();
$post->saveAllData($data); // careful, this could throw Exceptions