【问题标题】:CakePHP HABTM relationship saving new associationsCakePHP HABTM 关系保存新的关联
【发布时间】:2013-07-07 02:04:37
【问题描述】:

我在为我正在使用的某些代码保存我的 HABTM 关系时遇到了一些问题。我有 PodcastsCategories 在 HABTM 关系中。下面的代码和问题说明

模型/Podcast.php

class Podcast extends AppModel{
    public $hasMany = 'Episode';
    public $hasAndBelongsToMany = array(
        'Category' =>
            array(
                'className' => 'Category',
                'joinTable' => 'categories_podcasts',
                'foreignKey' => 'podcast_id',
                'associationForeignKey' => 'category_id',
                'unique' => false
            )
        );
}

型号/类别.php

class Category extends AppModel{
    public $hasAndBelongsToMany = array(
        'Podcast' =>
            array(
                'className' => 'Podcast',
                'joinTable' => 'categories_podcasts',
                'foreignKey' => 'category_id',
                'associationForeignKey' => 'podcast_id',
                'unique' => false
            )
        );
}

这就是我传递给saveAll() 的数组的样子

Array
(
    [Podcast] => Array
        (
            [name] => Mohr Stories - FakeMustache.com
            [description] => Join your host Jay Mohr and a rotating cast of his hilarious friends as they regale you with tales and conversation covering every topic imaginable. You haven't heard the half of it until you've heard... Mohr Stories.
            [website] => http://www.FakeMustache.com
        )

    [Category] => Array
    (
        [0] => 1
        [1] => 2
    )

)

效果很好 - 添加了播客并更新了连接表,但我的印象是我的 Category 数组可能如下所示:

 [Category] => Array
        (
            [0] => Array
                (
                    [name] => Test
                )

            [1] => Array
                (
                    [name] => Test2
                )

        )

这将保存新类别“Test”和“Test2”,然后使用新添加的 id 更新连接表。这是不可能的,还是我在这里遗漏了一些图片?

【问题讨论】:

  • I was under the impression - 基于什么文档?
  • 基于文档的保存您的数据页面的this section。他们在那里的示例数组和描述 “将上述数组传递给 saveAll() 将创建包含的标签,每个标签都与它们各自的配方相关联。”

标签: cakephp has-and-belongs-to-many cakephp-2.3


【解决方案1】:

您确实可以这样做,但使用另一种数据格式,其中每条记录都包含相关数据,如以下代码所示,允许保存 2 条记录:

array{
    array{
        'Podcast' => array {
             'id' => 25
         },
         'Category' => array {
             'name' => 'Test'
         }
    }
    array{
         'Podcast' => array {
             'id' => 25
         },
         'Category' => array {
             'name' => 'Test2'
         }
    }
}

将此数组传递给您的播客/类别模型之一的 saveAll 方法。

$this->Podcast->saveAll($myData);

但请注意,由于您没有为类别提供任何 ID,因此它们将被创建,即使存在同名的现有类别。

并且如果不存在 id 为 25 的 Podcast,则会创建它

【讨论】:

    猜你喜欢
    • 2023-03-07
    • 2010-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多