
php
Cakephp 3.1 不会保存简单的 hasMany 关系
在开发 web 应用程序时,数据之间的关系是非常重要的。Cakephp 是一个流行的 php 框架,它提供了简便的方式来管理数据库之间的关系。在 Cakephp 中,我们可以通过定义模型之间的关联关系来简化数据的操作和查询。然而,在 Cakephp 3.1 版本中,存在一个问题,即它不会自动保存简单的 hasMany 关系。问题描述在 Cakephp 中,我们可以使用 hasMany 关联来表示一个模型拥有多个关联模型的情况。例如,一个博客文章可以有多个评论。在模型层面,我们可以这样定义这种关系:phpclass Article extends Table { public function initialize(array $config) { $this->hasMany('Comments'); }}class Comment extends Table { public function initialize(array $config) { $this->belongsTo('Article'); }}在上面的例子中,Article 模型拥有多个 Comment 模型。问题原因然而,在 Cakephp 3.1 版本中,当我们保存一个 Article 模型时,并不会自动保存其关联的 Comment 模型。这是因为 Cakephp 3.1 引入了一个新的 ORM(对象关系映射)层,它对保存行为进行了重构。这个重构导致了 hasMany 关系的保存行为发生了变化。解决方案为了解决这个问题,我们需要手动保存关联的模型。在保存 Article 模型之前,我们需要遍历关联的 Comment 模型,并逐个保存它们。phppublic function saveArticle($data) { $article = $this->Articles->newEntity($data); if ($this->Articles->save($article)) { foreach ($article->comments as $comment) { $comment->article_id = $article->id; $this->Comments->save($comment); } return true; } return false;}在上面的例子中,我们使用了 $article->comments 来访问 Article 模型的关联 Comment 模型。通过遍历这些关联模型,我们可以为每个 Comment 模型设置正确的 article_id,并保存它们。案例代码下面是一个完整的案例代码,演示了如何手动保存简单的 hasMany 关系:phpclass ArticlesController extends AppController { public function add() { $article = $this->Articles->newEntity($this->request->data); if ($this->Articles->save($article)) { foreach ($article->comments as $comment) { $comment->article_id = $article->id; $this->Comments->save($comment); } $this->Flash->success(__('The article has been saved.')); return $this->redirect(['action' => 'index']); } $this->Flash->error(__('The article could not be saved. Please, try agAIn.')); $this->set(compact('article')); }}在上面的例子中,我们在保存 Article 模型时,手动保存了其关联的 Comment 模型。虽然 Cakephp 3.1 不会自动保存简单的 hasMany 关系,但我们可以通过手动保存关联模型来解决这个问题。这是一个临时的解决方案,希望在后续的版本中,Cakephp 能够恢复自动保存简单的 hasMany 关系的功能。Copyright © 2025 IZhiDa.com All Rights Reserved.
知答 版权所有 粤ICP备2023042255号