在 CakePHP 中为一个模型保存多条记录
我想为一个模型保存多条记录。如果没有出现问题,使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
首先,这个数据库设计需要标准化。
在我看来,
Notification
可以有许多与其相关的User
。同时,一个User
可以有多个Notification
。因此,在视图中,您可以简单地使用以下代码自动调出多选表单来获取用户 id:
发送到控制器的数据将是形式:
现在,您所要做的就是调用 saveAll() 函数而不是 save()。
这就是蛋糕的做法!
First off, this database design needs to be normalized.
It seems to me like a
Notification
can have manyUser
s related to it. At the same time, aUser
can have manyNotification
s. Therefore,In the view, you can simply use the following code to automagically bring up the multi-select form to grab user ids:
The data that is sent to the controller will be of the form:
Now, all you have to do is called the saveAll() function instead of save().
And that's the Cake way to do it!
这些值必须像这样重复
如果您不传递任何列值,这个蛋糕将忽略它
Those values have to be repeat like this
If you don't pass any column value, this cake will just ignore it
您必须调整表单的输出以适应
Model::saveAll
。在你的控制器中:在你的模型中:
这里的好处是你的控制器仍然对你的模型的模式一无所知,而它不应该知道。
事实上,您可能可以在模型中重新定义
saveAll
,它将正确格式化的输入数组交给parent::saveAll
,但会自行处理特殊情况。You're going to have to massage your form's output to suit
Model::saveAll
. In your controller:And in your model:
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 toparent::saveAll
, but handles special cases itself.可能有一种更简单的方法来做到这一点,但我使用了这种技术:首先,更改表单,以便获得如下所示的数组:(
只需将多选输入的名称更改为 selected_users.id)
然后循环用户 ID 并单独保存每条记录:
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:
(Just change the multiselect input's name to selected_users.id)
Then loop through the user ids and save each record individually: