在 CakePHP 中为一个模型保存多条记录

发布于 2024-10-04 05:21:13 字数 839 浏览 0 评论 0原文

我想为一个模型保存多条记录。如果没有出现问题,使用 saveAll() 可以很容易地完成此操作:

我有一个通知表单,我可以在其中从

Array([Notification] => Array
    (
        [user_id] => Array
            (
                [0] => 4
                [1] => 6
            )

        [subject] => subject
        [content] => the-content-here
    )
)

我读过 Cake 1.3 书,为了保存模型的多个记录,您必须拥有 < code>$this->data 类似:

Array([Article] => Array(
        [0] => Array
            (
                        [title] => title 1
                    )
        [1] => Array
            (
                        [title] => title 2
                    )
            )
)

那么,如何将主题和内容“共享”给所有选定的用户?

I would like to save several records for one model. This would have been done pretty easily with saveAll() if it hadn't been for a problem:

I have a notification form, where I select multiple users from a <select> and two fields, for subject and content respectively. Now, when I output what $this->data contains, I have:

Array([Notification] => Array
    (
        [user_id] => Array
            (
                [0] => 4
                [1] => 6
            )

        [subject] => subject
        [content] => the-content-here
    )
)

I've read on Cake 1.3 book, that in order to save multiple records for a model, you have to have the $this->data something like:

Array([Article] => Array(
        [0] => Array
            (
                        [title] => title 1
                    )
        [1] => Array
            (
                        [title] => title 2
                    )
            )
)

So, how do I 'share' the subject and content to all selected users?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

对不⑦ 2024-10-11 05:21:13

首先,这个数据库设计需要标准化。

在我看来,Notification 可以有许多与其相关的User。同时,一个User可以有多个Notification。因此,

  • 引入一个名为users_notifications的连接表。
  • 实现 HABTM 关系:通知 hasAndBelongsToMany User

在视图中,您可以简单地使用以下代码自动调出多选表单来获取用户 id:

echo $this->Form->input('User');

发送到控制器的数据将是形式:

Array(
    [Notification] => Array
        (
            [subject] => subject
            [content] => contentcontentcontentcontentcontentcontent
        ),
    [User] => Array
        (
            [User] => Array
                (
                    [0] => 4
                    [1] => 6
                )
         )
)

现在,您所要做的就是调用 saveAll() 函数而不是 save()。

$this->Notification->saveAll($this->data);

这就是蛋糕的做法!

First off, this database design needs to be normalized.

It seems to me like a Notification can have many Users related to it. At the same time, a User can have many Notifications. Therefore,

  • Introduce a join table named users_notifications.
  • Implement the HABTM Relationship: Notification hasAndBelongsToMany User

In the view, you can simply use the following code to automagically bring up the multi-select form to grab user ids:

echo $this->Form->input('User');

The data that is sent to the controller will be of the form:

Array(
    [Notification] => Array
        (
            [subject] => subject
            [content] => contentcontentcontentcontentcontentcontent
        ),
    [User] => Array
        (
            [User] => Array
                (
                    [0] => 4
                    [1] => 6
                )
         )
)

Now, all you have to do is called the saveAll() function instead of save().

$this->Notification->saveAll($this->data);

And that's the Cake way to do it!

撩起发的微风 2024-10-11 05:21:13

这些值必须像这样重复

Array([Notification] => Array(
        [0] => Array
            (
                        [user_id] => 4
                        [subject] => subjects
                        [content] => content
                    )
        [1] => Array
            (
                        [user_id] => 6
                        [subject] => subject
                        [content] => contents
                    )
            )
)


$this->Notification->saveAll($data['Notification']); // should work

如果您不传递任何列值,这个蛋糕将忽略它

Those values have to be repeat like this

Array([Notification] => Array(
        [0] => Array
            (
                        [user_id] => 4
                        [subject] => subjects
                        [content] => content
                    )
        [1] => Array
            (
                        [user_id] => 6
                        [subject] => subject
                        [content] => contents
                    )
            )
)


$this->Notification->saveAll($data['Notification']); // should work

If you don't pass any column value, this cake will just ignore it

故事未完 2024-10-11 05:21:13

您必须调整表单的输出以适应Model::saveAll。在你的控制器中:

function action_name()
{
    if ($this->data) {

        if ($this->Notification->saveMany($this->data)) {
            // success! :-)
        } else {
            // failure :-(
        }
    }
}

在你的模型中:

function saveMany($data)
{
    $saveable = array('Notification'=>array());

    foreach ($data['Notification']['user_id'] as $user_id) {

        $saveable['Notification'][] = Set::merge($data['Notification'], array('user_id' => $user_id));
    }

    return $this->saveAll($saveable);
}

这里的好处是你的控制器仍然对你的模型的模式一无所知,而它不应该知道。

事实上,您可能可以在模型中重新定义 saveAll,它将正确格式化的输入数组交给 parent::saveAll,但会自行处理特殊情况。

You're going to have to massage your form's output to suit Model::saveAll. In your controller:

function action_name()
{
    if ($this->data) {

        if ($this->Notification->saveMany($this->data)) {
            // success! :-)
        } else {
            // failure :-(
        }
    }
}

And in your model:

function saveMany($data)
{
    $saveable = array('Notification'=>array());

    foreach ($data['Notification']['user_id'] as $user_id) {

        $saveable['Notification'][] = Set::merge($data['Notification'], array('user_id' => $user_id));
    }

    return $this->saveAll($saveable);
}

The benefit here is your controller still knows nothing about your model's schema, which it shouldn't.

In fact, you could probably redefine saveAll in your model, which hands off correctly formatted input arrays to parent::saveAll, but handles special cases itself.

绅刃 2024-10-11 05:21:13

可能有一种更简单的方法来做到这一点,但我使用了这种技术:首先,更改表单,以便获得如下所示的数组:(

Array(
    [Notification] => Array
        (
            [subject] => subject
            [content] => contentcontentcontentcontentcontentcontent
        ),
    [selected_users] => Array
        (
            [id] => Array
                (
                    [0] => 4
                    [1] => 6
                )
         )
)

只需将多选输入的名称更改为 selected_users.id)

然后循环用户 ID 并单独保存每条记录:

foreach( $this->data[ 'selected_users' ][ 'id' ] as $userId ) {
    $this->data[ 'Notification' ][ 'user_id' ] = $userId;
    $this->Notification->create();  // initializes a new instance
    $this->Notification->save( $this->data );
}

There might be a more cakey way of doing this, but I've used this kind of technique: First, change the form so that you get an array like this:

Array(
    [Notification] => Array
        (
            [subject] => subject
            [content] => contentcontentcontentcontentcontentcontent
        ),
    [selected_users] => Array
        (
            [id] => Array
                (
                    [0] => 4
                    [1] => 6
                )
         )
)

(Just change the multiselect input's name to selected_users.id)

Then loop through the user ids and save each record individually:

foreach( $this->data[ 'selected_users' ][ 'id' ] as $userId ) {
    $this->data[ 'Notification' ][ 'user_id' ] = $userId;
    $this->Notification->create();  // initializes a new instance
    $this->Notification->save( $this->data );
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文