2

我有一个 Post 和 category 模型与 category_post 表有多对多的关系

在实际场景中,我想添加一个具有多个现有类别 ID 的帖子,例如

帖子有

   $postobj = new Post();
   $postobj->setTitle("First title");
   $postobj->setContent("First title");

我也有现有的带有 id 的类别

    $category_id = array(8,9,17,39)

我想将上述类别的帖子保存在一个保存功能中,例如

  $postobj->save();

我不知道我们怎么能做到这一点?

4

1 回答 1

1

好的,所以在测试之后,看起来 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
于 2013-04-16T15:23:54.543 回答