【问题标题】:Model Associations don't work correctly模型关联无法正常工作
【发布时间】:2012-11-19 10:08:37
【问题描述】:

我有两个模型。 PostModel & CommentModel。
我在这些类中定义了两个关系。

<?php
class PostModel extends AppModel {
    var $name = 'Post';
    var $hasMany = array(
        'Comment' => array(
            'className' => 'Comment',
            'foreignKey' => 'post_id'
        )
    );
}
 ?>

和

<?php 
class CommentModel extends AppModel {
var $name = 'Comment';
var $belongsTo = array(
    'Post' => array(
        'className' => 'Post',
        'foreignKey' => 'post_id'
    )
);
}
?>

在数据库中,我有带有 post_id 列的帖子表和 cmets 表。 当我使用此命令获取记录时,在 PostController 类中:

$this->set('post',$this->Post->findById($id)); 

调试 $post 数组我看到了这个数组:

array(
'Post' => array(
    'id' => '4',
    'title' => 'روز اول دانشگاه',
    'body' => 'سلام. روز اول بود که اومده بودیم '
    'created' => '2012-11-11 21:49:48',
    'modified' => null
)
)

我希望 [comment] 行在此数组中,但没有。

我在网上搜索并调试我的应用程序,但我无法解决这个问题。!!!!!!

注意:cakephp 版本是 2.2.3 稳定版

【问题讨论】:

  • 在模型末尾加上“Model”是不正常的。您的模型应该是 Post 和 Comment,而不是 PostModel 和 CommentModel。
  • 根据命名约定。
  • 我在最后清除了模型。但它们之间没有区别。
  • 这不是问题的答案 - 只是建议。
  • 你是对的,戴夫,错过了那个。当然它们的模型名称中没有模型;)所以只需“发布”(Post.php)和“评论”(Comment.php)来遵循约定。

标签: cakephp associations cakephp-2.0


【解决方案1】:

您的模型命名不正确。 PostModel 应该是带有 posts 表的 Post,CommentModel 应该是带有 cmets 表和 post_id 的 Comment。此外,这不起作用,因为您已告诉您的 Comments 模型在帖子表上查找“post_id”作为外键。这对于 Posts hasMany Comments 关系是不正确的,并且由于该列不存在,它将会失败。如果您关注the convention for Models,您实际上不需要将任何内容传递到数组中。 ORM 会解决的。

class Post extends AppModel {
    public $hasMany = array('Comment');
}
class Comment extends AppModel {
    public $belongsTo = array('Post');
}

【讨论】:

    【解决方案2】:

    你使用可包含的吗?如果没有,请这样做!

    public $actsAs = array('Containable');

    在你的模型中

    然后

    $this->Post->find('first', array(
        'conditions' => array('Post.id'=>$id), 
        'contain' => array('Comment'));
    

    您还应该像 Dave 指出的那样重命名您的模型。所以只需“Post extends AppModel”(Post.php)和“Comment extends AppModel”(Comment.php)来遵循约定。

    PS:然后您可以从模型中删除“var $name”。还从您的 php 文件中删除关闭 ?&gt;。最后但同样重要的是,将所有剩余的“var”重命名为“public”。

    【讨论】:

    • 他不能删除 $name,否则他的模型名称不正确。
    • 警告 (512):模型“发布”与模型“评论”无关 [CORE\Cake\Model\Behavior\ContainableBehavior.php,第 339 行]
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-21
    • 2017-01-15
    • 2012-05-29
    • 2020-04-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多