【问题标题】:CakePHP Saving HABTM relationship with same modelCakePHP 保存 HABTM 与同一模型的关系
【发布时间】:2013-05-08 12:12:27
【问题描述】:

我无法保存一些 HABTM 数据。

我的模型“Category”与其自身有一个称为“SubCategory”的 HABTM 关系

$this->Category->create();
$c["Category"]["display_order"] = $this->Category->getNextDisplayOrder();
$c["Category"]["title"] = $this->request->data["title"];
$c["SubCategory"]["category_id"] = $id; //The id of the parent category

$new_cat = $this->Category->saveAll($c);

这将创建我的新类别并将其保存在数据库中,但是 id 在子类别表中以错误的顺序保存。 (category_id => 我刚刚创建的新猫id,subcategory_id => parent_id)

知道为什么将 ID 保存在错误的列中吗?

这是我的 HABTM 关系

public $hasAndBelongsToMany = array(
        'SubCategory' => array(
            'className' => 'Category',
            'joinTable' => 'categories_subcategories',
            'foreignKey' => 'category_id',
            'associationForeignKey' => 'subcategory_id',
            'unique' => 'keepExisting',
            'conditions' => '',
            'fields' => '',
            'order' => '',
            'limit' => '',
            'offset' => '',
            'finderQuery' => '',
            'deleteQuery' => '',
            'insertQuery' => ''
        )
    );

【问题讨论】:

    标签: cakephp


    【解决方案1】:

    我被你的帖子弄糊涂了。

    如果

    $c["SubCategory"]["category_id"] = $id; //The id of the parent category
    

    这应该是刚刚创建的类别的 id 还是父类别?您在帖子中说了两件事。

    (category_id => 我刚刚制作的新猫id,subcategory_id => parent_id)

    无论哪种方式,如果您希望 id 是您刚刚创建的那个,则将该行更改为此

    $c["SubCategory"]["category_id"] = $this->Category->id;
    

    $c["SubCategory"]["category_id"] = $this->Category->getLastInsertID();
    

    【讨论】:

    • 我想创建一个类别,同时存储与它的父级($id)的关系
    猜你喜欢
    • 2011-08-12
    • 2010-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多